Jsch:命令输出不可用 [英] Jsch : Command Output unavailable
问题描述
我正在尝试使用jsch连接到远程开关并运行一些命令并提取输出。
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();
当我调试inputStream.isAvailable()时总是返回零,表明命令没有输出。
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();
输出 -
开放...
user @ host:〜> pwd
/ home / user
user @ host:〜>
user @ host:〜> exit
logout
Opening...
user@host:~> pwd
/home/user
user@host:~>
user@host:~> exit
logout
这篇关于Jsch:命令输出不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!