如何使用JSch执行交互式命令并从Java读取稀疏输出

时间:2015-04-27 15:21:08

标签: java ssh inputstream jsch

目前我可以使用JSch库在SSH会话中执行远程命令,如下所示:

JSch jsch = new JSch();
Session session = jsch.getSession(username, host, 22);
session.setPassword(password);

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

session.connect();

ChannelExec channel = (ChannelExec) session.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));

channel.setCommand("ls -l");
channel.connect();

StringBuilder output = new StringBuilder();

String s = null;
while((s = in.readLine()) != null){
    output.append(s + "\n");
}

System.out.println(output);

立即返回完整值的命令工作正常,但是一些交互式命令(如“Docker run”)每秒钟返回一次值(几分钟),而前面的代码只读取返回的第一个值

有没有办法读取命令返回的值?

修改

这是我现在的代码:

public String executeCommand(String cmd) {
    try {
        Channel channel = session.openChannel("shell");

        OutputStream inputstream_for_the_channel = channel.getOutputStream();
        PrintStream commander = new PrintStream(inputstream_for_the_channel, true);

        channel.setOutputStream(System.out, true);

        channel.connect();

        commander.println(cmd);

        commander.close();

        do {
            Thread.sleep(1000);
        } while(!channel.isEOF());
    } catch(Exception e) {
        e.printStackTrace();
    }
    return null;
}

1 个答案:

答案 0 :(得分:2)

实施JSch getInputStream的方式,其read似乎不仅会在会话/频道关闭时返回-1,而且还会在暂时没有输入数据的情况下返回channel.isClosed()

您最好使用examples/Sudo.java来测试会话/频道是否已关闭。见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)); } if(channel.isClosed()){ System.out.println("exit-status: "+channel.getExitStatus()); break; } try{Thread.sleep(1000);}catch(Exception ee){} }

channel.setOutputStream(System.out, true);

你的代码用&#34; shell&#34; channel在控制台上打印输出,因为您已通过以下方式指示它:

SELECT * FROM `table` WHERE
field LIKE '%" . base64_encode($term) . "%' 
OR field LIKE '%" . substr(base64_encode($term .'a'),0,-4) . "%' 
OR field LIKE '%" . substr(base64_encode($term .'aa'),0,-8) . "%' 
OR field LIKE '%" . substr(base64_encode($term .'aaa'),0,-12) . "%'

您必须实现输出流以写入字符串。见Get an OutputStream into a String

或者实际上,您应该能够使用与&#34; exec&#34;相同的代码。信道。