问题
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 know how I can get to know, if there was any error while execution of the command.
Following is my code
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();
回答1:
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
回答2:
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");
}
来源:https://stackoverflow.com/questions/40040770/jsch-exec-output-for-error