gpt4 book ai didi

java - 在远程服务器上运行多个命令

转载 作者:太空宇宙 更新时间:2023-11-04 10:43:09 25 4
gpt4 key购买 nike

到目前为止,我已经设法连接、运行单个命令然后断开连接。我遇到的问题是此后运行第二个、第三个等命令。

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 Downloadsls 之后的内容?

最佳答案

用“;”分隔你的命令例如:

String command1="cd mydeploy/tools/Deploy/scripts/; ls -ltr;./conn_testing.ksh";

关于java - 在远程服务器上运行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34154864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com