I have code which allow me to connect through ssh, run a command and get response back. It works fine but only for the non-interactive commands (like: ls
, df
which gives the result back immediately after their run). The problem is when I'm trying to run some interactive command like top
or passwd
code is waiting forever for the response (and of course getting none).
How to cope with interactive commands? I really don't care about the output, I just wanna to run it.
public String runCommand(String command) throws Exception {
// SSH Channel
ChannelExec channelssh = (ChannelExec) session.openChannel("exec");
// Execute command
channelssh.setCommand(command);
channelssh.connect();
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');
}
channelssh.disconnect();
return stringBuilder.toString();
}
1, You can use ChannelShell. Here is an example: Shell.java. And this post clarify differences between exec and shell: what's the exact differences between jsch ChannelExec and ChannelShell?
2, I tried ChannelExec.setPty(true). And in this way, I could get output. However, it didn't stop.