我需要在远程计算机上运行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();
答案 0 :(得分:1)
从“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
答案 1 :(得分:1)
如果您已经知道会发生哪种异常,我们可以使用以下方式。
您可以通过获取Input Stream来检查在远程主机中执行的命令的响应,然后根据您的成功条件解析该流。
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");
}