我正在尝试使用jsch连接到远程交换机并运行一些命令并提取输出。
我可以使用连接到交换机,但输入流中没有命令输出。也许我没有以正确的方式做到这一点。这是代码
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();
当我调试inputStream.isAvailable()时,总是返回零,表明该命令没有输出。
TIA!
答案 0 :(得分:4)
请尝试以下代码 - 经过测试和运作
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();
输出 -
打开...
用户@主机:〜&GT; PWD
/ home / user的
用户@主机:〜&GT;
用户@主机:〜&GT;退出
注销