【发布时间】: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 ();
}
【问题讨论】: