JSch Exec 错误输出

JSch Exec output for error

我需要 运行 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"频道的官方例子入手,不要重复造轮子:
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

如果你已经知道会发生什么样的异常,我们可以使用下面的方法。

您可以通过获取输入流来检查您在远程主机上执行的命令的响应,然后根据您的成功标准解析流。

        ChannelExec execChannel = (ChannelExec) session.openChannel("exec");
        List<String> executionResult = new ArrayList<>();
        execChannel.setErrStream(System.err);
        InputStream consoleInputStream = execChannel.getInputStream();
        String command = "./executeScript.sh"
        execChannel.setCommand(command);
        execChannel.connect();
        BufferedReader consoleReader = new BufferedReader(new 
        InputStreamReader(consoleInputStream));
        String consoleData;
        while ((consoleData = consoleReader.readLine()) != null) {
            executionResult.add(consoleData);
        }

        for (String resultLine : executionResult) {
            Pattern errorPattern = Pattern.compile(("(?i)\Exception\b"));
            Matcher errorMatcher = errorPattern.matcher(resultLine); 
            if (errorMatcher.find())
      logs.writeLog(Level.SEVERE, "Error occurred while executing command");
        }