到目前为止,我已经设法连接、运行单个命令然后断开连接。我遇到的问题是此后运行第二个、第三个等命令。
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";
关于java - 在远程服务器上运行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34154864/