gpt4 book ai didi

java - JSch Exec 错误输出

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:13:36 34 4
gpt4 key购买 nike

我需要在远程机器上运行 shell 脚本。我正在使用 JSch 连接到远程机器并使用 ChannelExec 执行 shell 脚本。我需要知道如何知道在执行命令时是否有任何错误。

以下是我的代码

ChannelExec channel = (ChannelExec) session.openChannel("exec");

BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
String command = scriptName;
if(parameter != null && !parameter.isEmpty()){
command += " " + parameter;
}

LOGGER.debug("Command To be Executed: " + command);

channel.setCommand(command);
channel.connect();

//capture output
String msg;

StringBuffer output = new StringBuffer();
while ((msg = in.readLine()) != null)
{
//output = output + msg;
output.append(msg);
}

LOGGER.debug("Output Message = " + output.toString());

LOGGER.debug("ERROR STATUS --" + channel.getExitStatus());

channel.disconnect();
session.disconnect();

最佳答案

从“exec” channel 的官方示例开始,不要重新发明轮子:
http://www.jcraft.com/jsch/examples/Exec.java.html

要读取错误,还要使用 ChannelExec.getErrStream 读取错误流。

或者将输出流和错误流合并为一个:
How to get one stream from error stream and input stream when calling a script using JSCH

关于java - JSch Exec 错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40040770/

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