我正在尝试将一些命令发送到路由器并尝试读取控制台输出。但问题是每次我发送一个新命令我得到相同的输出。我尝试在每个命令执行后创建一个新会话,但我仍然得到相同的输出。我在网上得到了一个样本,并根据我的需要进行了修改。当我将它作为一个独立的类运行时,它完美地运行。但是当部署在服务器上时,它似乎无法正常工作。说实话,我只是一天或两天我用过JSCH而且文档非常稀疏。
这是我的代码的读法:
private void writeCommand(String command) throws IOException, JSchException {
Channel channel = getChannel();
((ChannelExec) channel).setCommand(command.getBytes());
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
readChannelOutput(channel);
}
private void readChannelOutput(Channel channel) {
byte[] buffer = new byte[1024];
try {
InputStream inputStream = channel.getInputStream();
channel.connect();
while (true) {
while (inputStream.available() > 0) {
int i = inputStream.read(buffer, 0, 1024);
if (i < 0) {
break;
}
deviceOut.updateDeviceOutput(new String(buffer, 0, i));
}
if (channel.isClosed()) {
break;
}
}
disconnect();
} catch(IOException e) {
e.printstacktrace();
} catch (JSchException e) {
e.printstacktrace();
}
}
public Session getSession () throws Exception {
if (session == null || !session.isConnected()) {
session = connect(getUserid(), getIpaddress(), getPassword(), getPort());
}
return session;
}
protected Session connect(String userName, String hostname, String password, int port) throws Exception {
JSch jSch = new JSch();
try {
session = jSch.getSession(userName, hostname, port);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
logger.debug("Connecting SSH to " + getIpaddress() + " - Please wait for few seconds... ");
session.connect();
logger.debug("Connected!");
if (session.isConnected()) {
setConnectionState(DeviceConnection.LOGIN_COMPLETE);
} else {
setConnectionState(DeviceConnection.LOGIN_FAILED);
throw new Exception("Failed to login to device");
}
deviceOut = new DeviceOutput(getLogger());
return session;
} catch (JSchException e) {
disconnect();
e.printstacktrace();
} catch (PalException e) {
disconnect();
e.printstacktrace();
}
}
我要发送的命令是
term len 512
和
show running-config | include hostname
但输出保持不变。第一个命令甚至不应该有任何诚实的输出。我有什么问题吗?