首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jsch通过ssh连接到Diginet设备时检索python脚本输出

使用jsch通过ssh连接到Diginet设备时检索python脚本输出
EN

Stack Overflow用户
提问于 2012-03-01 05:51:49
回答 1查看 530关注 0票数 0

我正在使用jsch的ChannelExec连接到Digi传输WR21路由器,如果我执行一个命令,就说"modemstat ?“我可以捕获结果,但是如果我尝试运行一个python脚本,比如说"python hello.py“,那么我得到的结果都是"OK”,然后通道就会在我捕获脚本输出之前关闭。有人知道如何获得python脚本输出吗?

命令代码:

代码语言:javascript
复制
private void sendCommand(String ipAddress, String aCommand) {
    JSch jsch = new JSch();

    try {
        Session session = jsch.getSession("username", ipAddress, 22);
        session.setPassword("password");

        java.util.Properties config = new java.util.Properties(); 
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);

        session.connect(3*1000);

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(aCommand);

        channel.setInputStream(System.in);
        InputStream in = channel.getInputStream();

        channel.connect(3*1000);    
        StringBuilder commandOut = new StringBuilder();

        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)break;
                //System.out.print(new String(tmp, 0, i));
                //System.out.println(channel.getInputStream().toString());
                commandOut.append(new String(tmp, 0, i));

                //setChanged();
                //notifyObservers(System.err.toString() + "\n");
            }
            if (channel.isClosed()) {
                System.out.println("exit-status: "
                + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
                throw new JSchException("Cannot execute remote command: " + aCommand + " : " + ee.getMessage());
            }
        }

        channel.disconnect();
        session.disconnect();

        System.out.println(commandOut);


    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

从命令行运行时,script hello.py首先输出"OK“,然后大约一秒钟后输出"Hello World”。

EN

回答 1

Stack Overflow用户

发布于 2012-03-22 21:19:53

答案是两方面的。第一部分是我的命令末尾缺少"\r\n“,因此"python hello.py”应该是"python hello.py\r\n“。第二部分是我需要使用ChannelShell而不是ChannelExec。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9507245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档