I am trying to use jsch to connect to a remote switch and run some command and extract the output.
I am able to connect to the switch using , however the command output is not available in the inputstream. Maybe i am not doing it the right way. Here's the code
session = jsch.getSession("user", "10.0.0.0", 22);
session.setPassword("somepwd");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
System.out.println("connected to remote host");
Channel channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops);
channel.connect();
ps.println("show version");
ps.flush();
ps.close();
InputStream in=channel.getInputStream();
byte[] bt=new byte[1024];
while(in.available()>0)
{
int i=in.read(bt, 0, 1024);
if(i<0)
break;
String str=new String(bt, 0, i);
//displays the output of the command executed.
System.out.print(str);
}
channel.disconnect();
session.disconnect();
When i debug the inputStream.isAvailable() always returns zero suggesting that there is no output from the command.
TIA!
Please try the code below - tested and working
Channel channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops);
channel.connect();
ps.println("pwd");
ps.println("exit");
ps.flush();
ps.close();
InputStream in = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
System.out.println("Opening...");
String jarOutput;
while ((jarOutput = reader.readLine()) != null)
System.out.println(jarOutput);
reader.close();
channel.disconnect();
Output -
Opening...
user@host:~> pwd
/home/user
user@host:~>
user@host:~> exit
logout
来源:https://stackoverflow.com/questions/25761400/jsch-command-output-unavailable