到目前为止,我已设法连接,运行单个命令然后断开连接。我遇到的问题是之后运行第二个,第三个等命令。
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
,但这只会导致程序无效,所以我怀疑这不是可行的方法。
我应该添加什么来打印命令cd Downloads
和ls
之后的内容,例如在打印出第一个ls
输出后?
答案 0 :(得分:1)
使用";"分隔您的命令 例如:
String command1="cd mydeploy/tools/Deploy/scripts/; ls -ltr;./conn_testing.ksh";