JSch Exec output for error

故事扮演 提交于 2019-12-01 00:34:11
Martin Prikryl

Start with the official example for the "exec" channel, do not re-invent the wheel:
http://www.jcraft.com/jsch/examples/Exec.java.html

To read the error, read also the error stream using the ChannelExec.getErrStream.

Or merge the output and error streams into one:
How to get one stream from error stream and input stream when calling a script using JSCH

If you already know what kind of exception can occur, we can use the following way.

You can check the response of the command you executed in the remote host by getting Input Stream, and later parse the stream based on your success criteria.

        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");
        }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!