背景:
有一个中间件安装时需要检测服务器上jdk的版本,若版本非1.8或者没有安装则给出提示,写一个用ChannelExec写了一个工具类,但是拿不到服务端的执行结果,查了下资料需要使用ChannelShell,在这里做下记录。
通过ChannelShell在服务端执行命令,一直没有返回结果的主要原因是,最后执行exit命令,也就是说在你执行你想执行完你要执行的命令后需要加上exit命令,服务端才会确定你个命令的会话算是结束,并将交互信息以流的形式返回。
下面是代码
// 连接参数
String user = "";
String password= "";
String host= "";
Session session = jsch.getSession(user,password, host, 22);
Channel channel = null;
OutputStream outputstream_for_the_channel = null;
InputStream inputstream_from_the_channel = null;
PrintStream commander = null;
BufferedReader br = null;
try {
channel = session.openChannel("shell");
outputstream_for_the_channel = channel.getOutputStream();
commander = new PrintStream(outputstream_for_the_channel, true, ENCODING);
channel.connect();
commander.println(command);
// the important command
commander.println("exit");
commander.close();
inputstream_from_the_channel = channel.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream_from_the_channel, ENCODING));
String line;
while ((line = br.readLine()) != null) {
result.append(line);
LOGGER.info(line);
}
}
catch (JSchException e) {
LOGGER.error(e.getMessage());
}
catch (IOException e) {
LOGGER.error(e.getMessage());
}finally{
// 关流代码省略
}
session.disconnect();
参考