shamnu 上面的回答是正确的。我无法对其添加评论,因此这里有一些示例可以增强他的答案。一个是如何远程执行“ls -l”,另一个是“mkdir”,另一个是本地到远程复制。全部使用 0.1.51 版的 jsch ( http://www.jcraft.com/jsch/ ) 完成。
public void remoteLs() throws JSchException, IOException {
JSch js = new JSch();
Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22);
s.setPassword("mypassword");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
s.setConfig(config);
s.connect();
Channel c = s.openChannel("exec");
ChannelExec ce = (ChannelExec) c;
ce.setCommand("ls -l");
ce.setErrStream(System.err);
ce.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
ce.disconnect();
s.disconnect();
System.out.println("Exit code: " + ce.getExitStatus());
}
public void remoteMkdir() throws JSchException, IOException {
JSch js = new JSch();
Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22);
s.setPassword("mypassword");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
s.setConfig(config);
s.connect();
Channel c = s.openChannel("exec");
ChannelExec ce = (ChannelExec) c;
ce.setCommand("mkdir remotetestdir");
ce.setErrStream(System.err);
ce.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
ce.disconnect();
s.disconnect();
System.out.println("Exit code: " + ce.getExitStatus());
}
public void remoteCopy() throws JSchException, IOException, SftpException {
JSch js = new JSch();
Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22);
s.setPassword("mypassword");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
s.setConfig(config);
s.connect();
Channel c = s.openChannel("sftp");
ChannelSftp ce = (ChannelSftp) c;
ce.connect();
ce.put("/home/myuser/test.txt","test.txt");
ce.disconnect();
s.disconnect();
}