JSch Exec 错误输出

Muk*_*eja 5 java ssh jsch

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

以下是我的代码

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();
Run Code Online (Sandbox Code Playgroud)

Mar*_*ryl 1

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

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

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