本文整理汇总了Java中com.jcraft.jsch.JSch.getSession方法的典型用法代码示例。如果您正苦于以下问题:Java JSch.getSession方法的具体用法?Java JSch.getSession怎么用?Java JSch.getSession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.jcraft.jsch.JSch
的用法示例。
在下文中一共展示了JSch.getSession方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: listFiles
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
/**
* Lists directory files on remote server.
* @throws URISyntaxException
* @throws JSchException
* @throws SftpException
*/
private void listFiles() throws URISyntaxException, JSchException, SftpException {
JSch jsch = new JSch();
JSch.setLogger(new JschLogger());
setupSftpIdentity(jsch);
URI uri = new URI(sftpUrl);
Session session = jsch.getSession(sshLogin, uri.getHost(), 22);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
System.out.println("Connected to SFTP server");
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
Vector<LsEntry> directoryEntries = sftpChannel.ls(uri.getPath());
for (LsEntry file : directoryEntries) {
System.out.println(String.format("File - %s", file.getFilename()));
}
sftpChannel.exit();
session.disconnect();
}
示例2: testTestCommand
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
@Test
public void testTestCommand() throws JSchException, IOException {
JSch jsch = new JSch();
Session session = jsch.getSession("admin", "localhost", properties.getShell().getPort());
jsch.addIdentity("src/test/resources/id_rsa");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
ChannelShell channel = (ChannelShell) session.openChannel("shell");
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
channel.setInputStream(new PipedInputStream(pos));
channel.setOutputStream(new PipedOutputStream(pis));
channel.connect();
pos.write("test run bob\r".getBytes(StandardCharsets.UTF_8));
pos.flush();
verifyResponse(pis, "test run bob");
pis.close();
pos.close();
channel.disconnect();
session.disconnect();
}
开发者ID:anand1st,项目名称:sshd-shell-spring-boot,代码行数:24,代码来源:SshdShellAutoConfigurationWithPublicKeyAndBannerImageTest.java
示例3: executeCommand
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
public void executeCommand(final String command) throws IOException { // Cliente SSH final
JSch jsch = new JSch();
Properties props = new Properties();
props.put("StrictHostKeyChecking", "no");
try {
Session session = jsch.getSession(user, host, 22);
session.setConfig(props);
session.setPassword(password);
session.connect();
java.util.logging.Logger.getLogger(RemoteShell.class.getName())
.log(Level.INFO, session.getServerVersion());
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// Daqui para baixo é somente para imprimir a saida
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (in.available() > 0) {
continue;
}
System.out
.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
} catch (JSchException ex) {
java.util.logging.Logger.getLogger(RemoteShell.class.getName())
.log(Level.SEVERE, null, ex);
}
}
示例4: SSHShell
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
/**
* Creates SSHShell.
*
* @param host the host name
* @param port the ssh port
* @param userName the ssh user name
* @param sshPrivateKey the ssh password
* @return the shell
* @throws JSchException
* @throws IOException
*/
private SSHShell(String host, int port, String userName, byte[] sshPrivateKey)
throws JSchException, IOException {
Closure expectClosure = getExpectClosure();
for (String linuxPromptPattern : new String[]{"\\>", "#", "~#", "~\\$"}) {
try {
Match match = new RegExpMatch(linuxPromptPattern, expectClosure);
linuxPromptMatches.add(match);
} catch (MalformedPatternException malformedEx) {
throw new RuntimeException(malformedEx);
}
}
JSch jsch = new JSch();
jsch.setKnownHosts(System.getProperty("user.home") + "/.ssh/known_hosts");
jsch.addIdentity(host, sshPrivateKey, (byte[]) null, (byte[]) null);
this.session = jsch.getSession(userName, host, port);
this.session.setConfig("StrictHostKeyChecking", "no");
this.session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.connect(60000);
this.channel = (ChannelShell) session.openChannel("shell");
this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
channel.connect();
}
示例5: connectAndExecute
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
public static String connectAndExecute(String user, String host, String password, String command1) {
String CommandOutput = null;
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
// System.out.println("Connected");
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
// System.out.print(new String(tmp, 0, i));
CommandOutput = new String(tmp, 0, i);
}
if (channel.isClosed()) {
// System.out.println("exit-status: " +
// channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
// System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
return CommandOutput;
}
示例6: createSession
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
private Session createSession(String host, Args args) throws JSchException {
JSch jsch = new JSch();
for (String keyFile : getKeyFiles()) {
jsch.addIdentity(keyFile);
}
JSch.setLogger(new LogAdapter());
Session session = jsch.getSession(args.user, host, args.sshPort);
session.setConfig("StrictHostKeyChecking", "no");
return session;
}
示例7: testJschConnection
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
@Test
public void testJschConnection() throws InterruptedException, SftpException, JSchException, IOException {
JSch jsch = new JSch();
String passphrase = "";
jsch.addIdentity(privateKey,
StringUtil.isEmpty(passphrase) ?
null : passphrase);
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications",
"publickey,keyboard-interactive,password");
session.setConfig(config);
session.connect();
Thread.sleep(500);
session.disconnect();
}
示例8: transferFile
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
/**
* Transfer a file to remote destination via JSCH library using sFTP protocol
*
* @param username String remote SFTP server user name.
* @param password String remote SFTP server user password
* @param host String remote SFTP server IP address or host name.
* @param file File to transfer to SFTP Server.
* @param transferProtocol protocol to transfer a file. {@link FileTransferProtocol}
* @return boolean true if file is transfered otherwise false.
* @throws ApplicationException
*/
public static boolean transferFile(final String username, final String password, final String host,
final File file, final FileTransferProtocol transferProtocol)
throws ApplicationException {
// currently can deal with sftp only.
LOGGER.trace("Invoking transferFile...");
JSch jsch = new JSch();
try {
Session session = jsch.getSession(username, host);
LOGGER.debug("Session Host: " + session.getHost());
session.setPassword(password);
Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no");
session.setConfig(properties);
LOGGER.debug("Connecting to a session Host Server...");
session.connect();
LOGGER.debug("session is established with host server.");
Channel channel = session.openChannel(transferProtocol.ftpStringRepresentation());
LOGGER.debug("Connecting to a sftp Channel...");
channel.connect();
LOGGER.debug("Connected with sftp Channel.");
ChannelSftp channelSftp = (ChannelSftp) channel;
channelSftp.put(new FileInputStream(file), file.getName());
LOGGER.debug("File transfered successfully");
channelSftp.exit();
LOGGER.debug("sftp channel disconnected.");
channel.disconnect();
LOGGER.debug("channel disconnected.");
session.disconnect();
LOGGER.debug("session disconnected.");
return true;
} catch (JSchException | FileNotFoundException | SftpException e) {
LOGGER.error(e.getMessage(), e.getCause());
throw new ApplicationException(e.getMessage(), ApplicationSeverity.ERROR, e.getCause(), e);
}
}
示例9: connect
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
/**
* Connects to and maintains a ssh connection. If this method is called
* twice, a reconnection is attempted
*
* @throws SshException If the members of the SshConnection class are not properly set or if
* there was a problem actually connecting to the specified host.
* @throws IllegalStateException If connect() was called once successfully. connect() and any setter
* method can't be called after successfully connecting without first
* disconnecting.
*/
public void connect() throws SshException {
exceptIfAlreadyConnected();
try {
JSch jsch = new JSch();
validateMembers();
if (this.usePrivateKey) {
jsch.addIdentity(this.privateKeyFile.getAbsolutePath());
}
this.sshSession = jsch.getSession(this.username, this.host, this.port);
this.sshSession.setConfig(SSH_PROPERTIES);
if (!this.usePrivateKey && this.password != null) {
this.sshSession.setPassword(this.password);
}
this.sshSession.connect();
} catch (JSchException e) {
throw new SshException(e);
}
}
示例10: ssh
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
private static void ssh(String user, String passwd, String host){
try{JSch jsch = new JSch();
session = jsch.getSession(user, host, 22);
session.setPassword(passwd);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("shell");
channel.connect();
Thread.sleep(1000);
channel.disconnect();
session.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}
示例11: initializeSftp
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
private void initializeSftp(){
try{
JSch jsch = new JSch();
session = jsch.getSession(RunnerRepository.user, RunnerRepository.host, 22);
session.setPassword(RunnerRepository.password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
connection = (ChannelSftp)channel;
} catch (Exception e){
e.printStackTrace();
}
}
示例12: userpassword
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
public static boolean userpassword(String user,String password, String host){
boolean passed = false;
try{
JSch jsch = new JSch();
session = jsch.getSession(user, host, 22);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
connection = (ChannelSftp)channel;
try{USERHOME = connection.pwd();}
catch(Exception e){
System.out.println("ERROR: Could not retrieve remote user home directory");}
REMOTECONFIGDIRECTORY = USERHOME+"/twister/config/";
passed = true;
}
catch(JSchException ex){
if(ex.toString().indexOf("Auth fail")!=-1)
System.out.println("wrong user and/or password");
else{ex.printStackTrace();
System.out.println("Could not connect to server");}}
// }
return true;}
示例13: scpFileFromRemoteServer
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
/**
*
* Scp file from remote server
*
* @param host
* @param user
* @param password
* @param remoteFile
* @param localFile
* @throws JSchException
* @throws IOException
*/
public void scpFileFromRemoteServer(String host, String user, String password, String remoteFile, String localFile) throws JSchException, IOException {
String prefix = null;
if (new File(localFile).isDirectory()) {
prefix = localFile + File.separator;
}
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo userInfo = new UserInformation(password);
session.setUserInfo(userInfo);
session.connect();
// exec 'scp -f remoteFile' remotely
String command = "scp -f " + remoteFile;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
readRemoteFileAndWriteToLocalFile(localFile, prefix, out, in, buf);
session.disconnect();
}
示例14: sshCall
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
protected void sshCall(String username, String password, SshExecutor executor, String channelType) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, props.getShell().getHost(), props.getShell().getPort());
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel(channelType);
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
channel.setInputStream(new PipedInputStream(pos));
channel.setOutputStream(new PipedOutputStream(pis));
channel.connect();
try {
executor.execute(pis, pos);
} finally {
pis.close();
pos.close();
channel.disconnect();
session.disconnect();
}
} catch(JSchException | IOException ex) {
fail(ex.toString());
}
}
示例15: executeSSH
import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
private boolean executeSSH(){
//get deployment descriptor, instead of this hard coded.
// or execute a script on the target machine which download artifact from nexus
String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &";
try{
System.out.println("Executing "+ command);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession("rajeshrv", "localhost", 22);
session.setPassword("rajeshrv");
session.setConfig(config);
session.connect();
System.out.println("Connected");
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int index = 0;
while ((line = reader.readLine()) != null) {
System.out.println(++index + " : " + line);
}
channelExec.disconnect();
session.disconnect();
System.out.println("Done!");
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}