ChannelShell和服务端交互并获取服务端执行结果

85 篇文章 0 订阅

背景:

有一个中间件安装时需要检测服务器上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();

 参考

使用jsch中ChannelShell,使用readline方法读取执行结果时,被阻塞

ChannelShell 和 ChannelExec的区别

http://www.jcraft.com/jsch/examples/Shell.java.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独步秋风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值