使用 JSch 在 Unix 主机上高效地执行依赖于另一个长 运行 命令的多个命令

Efficiently execute multiple commands that depend on another long running command on Unix host with JSch

我需要在 Java 的远程 SSH 服务器上执行命令。为此,我正在使用 JSch。

命令 1 是在 Linux 机器上设置环境的命令,需要一些时间来执行(大约 20 分钟)。命令 1 是一次性操作。 如果我打开一个 PuTTY 会话,我只需要执行命令 1 一次。

命令 2 依赖于命令 1。没有命令 1 它不会执行。

Command 1执行完成后(一次操作),Command 2(需要2-3秒执行)可以针对不同的实体执行,而无需再次执行Command 1。

我知道我可以用 && 分隔的命令来完成它,但那样的话,命令 1 将执行不必要的降低整体性能。

代码:

String host = "1.1.1.1";
String user = "parag";
String password = "abcdf";
String command1 = "command1";
String command2 = "command2";
try {

    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host, 22);
    session.setConfig(config);
    session.setPassword(password);
    session.connect();
    System.out.println("Connected");

    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command1 + " && " + command2);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);

    InputStream in = channel.getInputStream();
    channel.connect();
    byte[] tmp = new byte[1024];
    while (true) {
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            System.out.print(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
            System.out.println("exit-status: " + channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
    }
    channel.disconnect();
    session.disconnect();
    System.out.println("DONE");
} catch (Exception e) {
    e.printStackTrace();
}

如果可行,请告诉我。如果有的话,也建议一个替代方案,以防 JSch 无法做到这一点。

你现在的方法是正确的。

如果您真的需要对其进行优化,则必须将命令提供给远程 shell 会话。使用“exec”通道显式启动 shell。或者直接使用“shell”频道。然后将各个命令写入 shell 输入。

另请参阅:

  • What is the difference between the 'shell' channel and the 'exec' channel in JSch
  • Multiple commands through JSch shell
  • JSch Shell channel execute commands one by one testing result before proceeding

强制警告:不要使用StrictHostKeyChecking=no盲目接受所有主机密钥。这是一个安全漏洞。您失去了针对 MITM attacks. For the correct (and secure) approach, see:

的保护