【问题标题】:JSch: Run command after Multi-Level sshJSch:在多级 ssh 之后运行命令
【发布时间】:2017-03-19 09:48:40
【问题描述】:

我正在使用JSch在多级ssh之后运行一些命令:

public static void main(String[] args) {

    String user="User0";
    String ip="IP0";
    int port=22;
    String password="Password0";
            JSch jsch= new JSch();
            Session session=null;
            ChannelExec channel=null;
            try {
                session=(jsch.getSession(user, ip, port));
                session.setConfig("StrictHostKeyChecking", "no");
                session.setPassword(password);
                session.connect();
                String dir=Reomte_DIR;  
                String cmd1=SomeComplexCommand;
                String cmd2=SomeMoreComplexCommand;
                channel = (ChannelExec) session.openChannel("exec");
                channel.setInputStream(null);
                channel.setCommand("ssh User1@IP1_PasswordLessLogin;ssh User2@IP2_PasswordLessLogin; "+cmd1+" ; "+cmd2+" ;");
                channel.setPty(true);
                channel.connect(4000);
                String res = null;
                    BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
                    BufferedReader error = new BufferedReader(new InputStreamReader(channel.getErrStream()));
                    if ((res = error.readLine()) == null) {
                        res = input.readLine()+input.readLine()+input.readLine()+input.readLine();
                    } else {

                        res = "-1";
                    }
                System.out.println("result:"+res);

            } catch (JSchException e) {
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }finally {
                channel.disconnect();
                session.disconnect();
            }       
        }

但它没有给出预期的结果。

事实上channel.getInputStream() 挂起。如果我删除多级 ssh,一切正常! 难道我做错了什么??

我得到了一些提示:Multi-level SSH login in JavaMultiple commands using JSch,但我无法让我的代码运行。

【问题讨论】:

  • 你的命令错了,你是不是先在命令行上试过?

标签: java ssh jsch


【解决方案1】:

你的命令是错误的。

您的命令将执行第一个命令ssh User1@IP1_PasswordLessLogin

然后它会在执行第二个命令之前等待它完成。

  • 第一个ssh 命令永远不会完成,因为它将永远等待用户输入命令。
  • 即使第一个ssh 完成,第二个ssh 也会在初始主机上执行,而不是IP1

你需要这样的东西:

ssh User1@IP1_PasswordLessLogin ssh User2@IP2_PasswordLessLogin "<cmd1> ; <cmd2>"

这告诉第一个sshIP1 上执行第二个ssh;第二个sshIP2 上执行&lt;cmd1&gt; ; &lt;cmd2&gt;

【讨论】:

    猜你喜欢
    • 2011-01-25
    • 2014-04-26
    • 2017-08-13
    • 2015-01-24
    • 1970-01-01
    • 2017-11-16
    • 2014-06-21
    • 2012-08-24
    • 1970-01-01
    相关资源
    最近更新 更多