问题
I've been trying to figure out this problem for hours now and I cant seem to figure it out. I'm trying to use JSch to SSH to a Linux computer from an Android phone. The commands always work fine but the output of the channel is usually empty. Sometimes it displays the output but most of the time it doesn't. Here's the code that I found online.
String userName = "user";
String password = "test123";
String connectionIP = "192.168.1.13";
JSch jsch = new JSch();
Session session;
session = jsch.getSession(userName, connectionIP, 22);
session.setPassword(password);
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
// SSH Channel
ChannelExec channelssh = (ChannelExec) session.openChannel("exec");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
channelssh.setOutputStream(baos);
// Execute command
channelssh.setCommand("ls");
channelssh.connect();
channelssh.disconnect();
RESULT = baos.toString();
RESULT is usually empty. If I change the command to mkdir or something of that nature the files show up on the Linux computer which leads me to believe that the command part is working correctly. The problem seems to lie within the ByteArrayOutputStream. I've also tested the connectionip, username and password on a different computer through Terminal so I know the credentials are correct. I've Googled this problem to death, any input would help me out significantly!
回答1:
Found the answer I was reading the wrong stream. Heres the proper code for others with this problem.
InputStream inputStream = channelssh.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line);
stringBuilder.append('\n');
}
return stringBuilder.toString();
回答2:
The exec-channel will be run on the other thread, so you need to wait for its termination before invoking Channel#disconnect().
来源:https://stackoverflow.com/questions/14863297/ssh-output-always-empty