如果输出大小很大,JSch终端输出读取失败

时间:2014-09-12 12:06:52

标签: java jsch

我正在尝试使用JSch在远程机器上执行cat命令并读取输出。如果文件很小,我会得到输出。但如果文件大小很大,我没有得到输出,命令的执行被绞死。

请建议我如何解决这个问题

部分代码:

JSch jSch = new JSch();
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
command = "cat test1.properties"
Session jsession = jSch.getSession(this.username, this.host, 22);
jsession.setPassword(this.password);
jsession.setConfig("StrictHostKeyChecking", "no");
jsession.connect();
Channel channel = jsession.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);
channel.connect();
boolean isPasswordEntered=false;
boolean isYesOrNoEntered=false;
StringBuilder sb = new StringBuilder();
byte[] tmp = new byte[1024];

int timeout = 60*1000;
long end = System.currentTimeMillis() + timeout; // 60 seconds * 1000 ms/sec , max 5 minutes 
InputStream in = channel.getInputStream();

while (true){
    if (System.currentTimeMillis()>end){
        break;
    }
    while (in.available() > 0) {
        end = System.currentTimeMillis()+timeout;
        int i = in.read(tmp, 0, 1024);
        if (i < 0) {
            break;
        }
        sb.append(new String(tmp, 0, i));
        if (!isYesOrNoEntered && sb.indexOf("yes")!=-1){ 
            isYesOrNoEntered = true;
            print.println("yes");
            Thread.sleep(500);
        }
        if (!isPasswordEntered && sb.toString().toLowerCase().indexOf("password")!=-1){     
            isPasswordEntered = true;
            print.println(nsmailPassword);
            LOG.debug("entering the nsmail password");
            Thread.sleep(500);
        }
    }
    if (channel.isClosed()) {
        if (in.available() > 0) {
            continue;
        }
        break;
    }           
}

1 个答案:

答案 0 :(得分:1)

要通过ssh读取远程文件,使用sftp比使用纯ssh更好。 Jsch内置了对sftp的支持。打开会话后,执行此操作以打开sftp频道:

ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");

一旦您打开了一个sftp频道,there are methods就可以读取一个远程文件,该文件允许您将该文件的内容作为InputStream访问:

InputStream stream = sftp.get("/some/file");

如果您需要逐行阅读,可以将其转换为阅读器:

InputStream stream = sftp.get("/some/file");
try {
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    // read from br
} finally {
    stream.close();
}