JSch Exec output for error

后端 未结 2 2047
孤街浪徒
孤街浪徒 2021-01-06 16:23

I need to run shell script at a remote machine. I am using JSch to connect to the remote machine and executing the shell script using ChannelExec. I need to kno

2条回答
  •  醉酒成梦
    2021-01-06 16:33

    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 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");
            }
    

提交回复
热议问题