/**
* 执行相关的命令
*/
public String execCmd(String command) throws Exception {
ChannelExec channelExec = null;
InputStream in = null;
StringBuffer buf = null;
try {
channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand(command);
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
in = channelExec.getInputStream();
channelExec.connect();
int res = -1;
buf = new StringBuffer(1024);
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
buf.append(new String(tmp, 0, i));
}
if (channelExec.isClosed()) {
res = channelExec.getExitStatus();
System.out.println(format("Exit-status: %d", res));
break;
}
}
} finally {
if (channelExec != null) {
channelExec.disconnect();
channelExec = null;
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
LOG.debug(e);
}
in = null;
}
}
return buf.toString();
}
添加回复
请先登陆