Reputation: 349
I am trying to execute a cat command on remote machine using JSch and reading the output.I gets output in case file is small. but if file size is large, I am not getting output and execution of command gets hanged.
please suggest me how to over come this problem
part of the code:
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;
}
}
Upvotes: 1
Views: 1104
Reputation: 25439
To read a remote file through ssh, you're better off using sftp than pure ssh. Jsch has built-in support for sftp. Once you've opened a session, do this to open an sftp channel:
ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
Once you've opened an sftp channel, there are methods to read a remote file which let you access the file's content as an InputStream:
InputStream stream = sftp.get("/some/file");
You can convert that to a Reader if you need to read line-by-line:
InputStream stream = sftp.get("/some/file");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
// read from br
} finally {
stream.close();
}
Upvotes: 1