【问题标题】:run multiple commands on remote server在远程服务器上运行多个命令
【发布时间】:2015-12-08 11:35:33
【问题描述】:

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

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 Downloadsls 之后的内容,例如在打印第一个ls 输出之后?

【问题讨论】:

  • 你能不能说得更具体些。您尝试连接到哪里,是 ssh 还是其他?
  • 您发布的代码看起来只运行一个命令,所以我想它工作正常吗?您可以编辑您的帖子以包含您编写的不起作用的代码吗?并准确解释它是如何失败的?
  • @Kenster:我添加了损坏的代码

标签: java linux ssh jsch


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    相关资源
    最近更新 更多