![](/img/trans.png)
[英]Java library to run multiple unrelated commands on a remote server via ssh
[英]run multiple commands on remote server
到目前为止,我已经设法连接,运行单个命令然后断开连接。 我遇到的问题此后正在运行第二,第三等命令。
public static void main(String args[]) {
try {
JSch js = new JSch();
Session session = js.getSession("myuser", "myhost", 22);
session.setPassword("mypassword");
Properties properties = new Properties() {
{
put("StrictHostKeyChecking", "no");
}
};
session.setConfig(properties);
session.connect();
Channel channel = session.openChannel("exec");
ChannelExec channelExec = (ChannelExec) channel;
channelExec.setCommand("ls");
channelExec.setErrStream(System.err);
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// This part doesn't work. It causes the program to hang.
// BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(channelExec.getOutputStream()));
// writer.write("cd Downloads");
// writer.write("ls");
// reader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
// while ((line = reader.readLine()) != null) {
// System.out.println(line);
// }
channelExec.disconnect();
session.disconnect();
System.out.println("Exit code: " + channelExec.getExitStatus());
} catch (JSchException | IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
我已经尝试使用ChannelExec
OutputStream
但这只是导致程序什么都不做,所以我怀疑那不是路。
例如,在打印第一个ls
输出之后,应按照cd Downloads
和ls
命令添加什么内容来打印内容?
用“;”分隔命令 例如:
String command1="cd mydeploy/tools/Deploy/scripts/; ls -ltr;./conn_testing.ksh";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.