jsch运行一个远程python文件,我只能在python完成后得到输出

时间:2016-06-06 11:12:27

标签: python jsch

我正在使用jsch“exec”来运行python文件。我只在python结束后得到输出。它很奇怪。它应该在进程运行时获得输出。 java代码是

package com.demo.jsch;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.*;

public class App3 {
public static void main(String[] args) throws JSchException, IOException {
    JSch jSch = new JSch();
    String user = "root";
    String host = "10.17.1.183";
    int port = 22;
    String password = "whoami!";
    String cmd = "source /etc/profile; /home/script/test.py";

    Session session = jSch.getSession(user, host, port);
    session.setPassword(password);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect(30000);
    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(cmd);

    BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream(), "utf8"));
    OutputStream out = channel.getOutputStream();

    channel.connect();

    String line = null;
    while (true) {
        line = in.readLine();
        if(line != null){
            System.out.println(line);
        }else{
            if(channel.isClosed()){
                System.out.println("退出状态" + channel.getExitStatus());
                break;
            }else{
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

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

python文件test.py是

#!/usr/bin/python
#-*- coding: utf-8 -*-
import sys,time
for i in range(0,10):
     print "line "+str(i)
     time.sleep(1)

test.py应该每1秒输出一次,但是我的jsch.java在10秒之前没有输出,它会立即获得所有输出。

0 个答案:

没有答案