我使用jsch的ChannelExec连接到Digi Transport WR21路由器,如果我执行命令,请说“modemstat?”我可以捕获结果但是如果我尝试运行python脚本,说“python hello.py”我得到的所有“OK”然后通道关闭然后我才能从脚本中捕获输出。有人知道如何输出python脚本吗?
命令代码:
private void sendCommand(String ipAddress, String aCommand) {
JSch jsch = new JSch();
try {
Session session = jsch.getSession("username", ipAddress, 22);
session.setPassword("password");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(3*1000);
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(aCommand);
channel.setInputStream(System.in);
InputStream in = channel.getInputStream();
channel.connect(3*1000);
StringBuilder commandOut = new StringBuilder();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)break;
//System.out.print(new String(tmp, 0, i));
//System.out.println(channel.getInputStream().toString());
commandOut.append(new String(tmp, 0, i));
//setChanged();
//notifyObservers(System.err.toString() + "\n");
}
if (channel.isClosed()) {
System.out.println("exit-status: "
+ channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
throw new JSchException("Cannot execute remote command: " + aCommand + " : " + ee.getMessage());
}
}
channel.disconnect();
session.disconnect();
System.out.println(commandOut);
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
从命令行运行时,脚本hello.py首先输出“OK”然后大约一秒后输出“Hello World”。
答案 0 :(得分:1)
答案是双重的。第一部分是我在命令结束时缺少“\ r \ n”,因此“python hello.py”应该是“python hello.py \ r \ n”。第二部分是我需要使用ChannelShell而不是ChannelExec。