【问题标题】:Performance takes a hit while using Java JSch "exec" vs "shell" to run multiple commands?使用 Java JSch“exec”与“shell”运行多个命令时性能会受到影响吗?
【发布时间】:2021-10-01 20:00:12
【问题描述】:

我已经测试了使用“exec”和“shell”通道使用 Java JSch 库发送多个命令的性能差异。我发现“exec”需要双倍的时间。例如,我使用命令 ls /etc/***,并发送 10、100、500 和 1000 次。它们的行为都相似,有时差异可达 15 秒。

我知道我可以以cm1;cm2;cm3 等形式发送多个命令,但这不是我想要的测试。

有没有人有过使用 shell 和 exec 的类似经历?

我发布了这两种测试的一些代码(部分代码来自其他人编写的同一个站点)。

使用外壳: 对于 shell 通道,我发送ls /etc/; echo "END_OF_COMMAND"

...
...
...
session = getSession (username, password, host);

ByteArrayOutputStream outputStream = new ByteArrayOutputStream ();
ChannelShell channel = (ChannelShell) session.openChannel ("shell");
channel.setOutputStream (outputStream);
PrintStream stream = new PrintStream (channel.getOutputStream ());
channel.connect ();

for (int i = 0; i < trials; i++) {
    System.out.println("Trial #" + i);
    stream.println (cmd);
    stream.flush ();

    String output = getCmdOutput (outputStream);
}

channel.disconnect ();
session.disconnect ();
...
...
...
public static String getCmdOutput (ByteArrayOutputStream outputStream) throws InterruptedException {
    while (outputStream.toString ().indexOf ("\nEND_OF_COMMAND") <= 0) {}

    String output = outputStream.toString ();
    outputStream.reset ();

    return output;
}

使用 exec:

...
...
...
for (int i = 0; i < trials; ++i) {
    System.out.println("Trial #" + i);
    execCmd(session, cmd);
}
...
...
...
public static void execCmd (Session session, String cmd) {
    ChannelExec channel = null;

    try {
        channel = (ChannelExec) session.openChannel ("exec");
        InputStream in = channel.getInputStream();

        channel.setCommand (cmd);
        channel.setPty(true);
        channel.connect ();

        String output = readOuput(in);
    }
    catch (Exception e) {
        e.printStackTrace ();
    }
    finally {
        if (channel != null && channel.isConnected ()) {
            System.out.println("Channel Exit Code: " + channel.getExitStatus());
            channel.disconnect ();
        }
    }
}

public static String readOuput (InputStream in) throws IOException {
    StringBuilder sb = new StringBuilder ();

    try (BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(in)))) {
        String line;

        while ((line = br.readLine ()) != null) {
            sb.append (line + System.lineSeparator ());
        }
    }

    return sb.toString ();
}

【问题讨论】:

    标签: java shell ssh jsch


    【解决方案1】:

    是的,很有可能。 “exec”通道在隔离环境(通常是新的 shell 实例)中运行命令。

    在服务器上设置环境可能需要一些时间

    所以它很可能与您的 Java 代码无关。

    【讨论】:

    • 好吧,看来创建新通道和附加新外壳实例的所有开销都是开销。感谢您的回复。
    猜你喜欢
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多