【发布时间】:2019-05-29 23:53:37
【问题描述】:
我正在使用 JSch 在远程 linux 服务器上运行 sudo 命令。
下面的示例显示了尝试 cd 进入目录并返回内容。我正在测试myDirectory 不存在的用例。
public static List<String> executeExecCommand() {
try {
Session session = new JSch().getSession() // paraphrasing for brevity
Channel channel - session.openChannel("exec");
String command = "echo \"password\" | sudo -S bash -c \"cd myDirectory/ && ls -la \"";
((ChannelExec(channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec(channel).setErrStream(System.err);
InputStream input = channel.getInputStream();
channel.connect();
List<String> output = new ArrayList<>();
try {
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader bufferedReader = new BufferedReader(InputReader);
String line = null;
while (true) {
while ((line = bufferedReader.readLine()) != null) {
output.add(line);
System.out.println("here is a line " + line);
}
if (channel.isClosed()( {
if (input.available() > 0) {
continue;
}
logger.DEBUG("exit status " + channel.getExitStatus());
break;
}
bufferedReader.close();
inputReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
channel.disconnect();
session.disconnect();
return output;
} catch (Throwable t) {
throw new JSchException("executeExecCommand : unable to establish SSH session " + t.toString());
}
}
从 intelliJ 中的单元测试运行时,我得到如下输出:
.
.
[sudo] password for username : bash: line 0: cd: myDirectory/: No such file or directory
2019-01-03 10:40:18 DEBUG [main] <Filename>:<linenumber> - exit status: 1
.
.
这是意料之中的,但我的问题是如何以编程方式访问 [sudo] 输出行?我查看了 ErrorStream 但它不包含在 intelliJ 的输出控制台上输出和显示的文本。
注意System.out.println("here is a line " + line);这一行没有被执行。
另请注意,从命令提示符运行时不会输出 [sudo] 行:即“mvn test”
那么,如何以编程方式访问 [sudo] 输出行?
【问题讨论】: