JSch:多级 ssh 后的 运行 命令

JSch: Run command after Multi-Level ssh

我正在使用 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 Java and Multiple commands using JSch 那里得到了一些提示,但我无法获得我的代码 运行ning。

你的命令有误。

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

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

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

你需要这样的东西:

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

这告诉第一个 sshIP1 上执行第二个 ssh;第二个 sshIP2.

上执行 <cmd1> ; <cmd2>