gpt4 book ai didi

java - 为什么在调用 Session::execCommand() 后会引发 IOException?

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:20 25 4
gpt4 key购买 nike

我正在尝试使用 SSH 协议(protocol)在远程计算机上运行服务。我使用 Ganymed SSH-2 for Java 库(版本 262),执行单个命令时效果很好,但在单个 session 期间尝试执行多个命令时我遇到了一些困难。

您能帮我找出引发 IOException 的原因以及如何修复它吗?

请在下面的摘录中找到代码:

private static void executeShellCommands(Connection connection, List<String> commandList) throws Exception {
Session session = connection.openSession();
InputStream stdout = new StreamGobbler(session.getStdout());
session.requestDumbPTY();
session.startShell();
for(String command : commandList) {
// The next line throws java.io.IOException
session.execCommand(command);
try (BufferedReader br = new BufferedReader(new InputStreamReader(stdout))) {
String line = br.readLine() + "\n";
StringBuilder shellOutput = new StringBuilder();
while (line != null) {
shellOutput.append(line);
line = br.readLine() + "\n";
}
}
}
session.close();
}

堆栈跟踪是:

java.io.IOException: A remote execution has already started.

at ch.ethz.ssh2.Session.execCommand(Session.java:282)
at ch.ethz.ssh2.Session.execCommand(Session.java:260)
at com.myproject.test.ssh.util.SshOperations.executeShellCommands(SshOperations.java:124)
at com.myproject.test.ssh.util.SshOperations.runBatchProcessingService(SshOperations.java:147)
at com.myproject.test.ssh.step.definitions.DocumentBatchProcessingStepDefs.testFileIsCopiedToBpsViaSSH(DocumentBatchProcessingStepDefs.java:97)
at ✽.Given test file is copied to BPS via SSH (myrepo/src/test/resources/cucumber/Regression.feature:21)

提前谢谢您。

最佳答案

ch.ethz.ssh2.Session的Javadoc中提到了

A Session is a remote execution of a program. "Program" means in this context either a shell, an application or a system command [.... ] Only one single program can be started on a session. However, multiple sessions can be active simultaneously.

我认为您应该使用多个 session ,例如如下所示:

private static void executeShellCommands(Connection connection, List<String> commandList) throws Exception {
for(String command : commandList) {
Session session = connection.openSession();
InputStream stdout = new StreamGobbler(session.getStdout());
session.requestDumbPTY();
session.startShell();
session.execCommand(command);
try (BufferedReader br = new BufferedReader(new InputStreamReader(stdout))) {
String line = br.readLine() + "\n";
StringBuilder shellOutput = new StringBuilder();
while (line != null) {
shellOutput.append(line);
line = br.readLine() + "\n";
}
}
session.close();
}
}

关于java - 为什么在调用 Session::execCommand() 后会引发 IOException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47811402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com