远程采集服务器信息,比如说磁盘信息、内存信息。
现介绍java通过SSH执行命令采集服务器信息,比如说执行df、ls、top。
代码语言:javascript复制/**
*
* SSH远程执行shell类
*/
public class SSHSession implements IRemoteSession {
/** SSH连接 */
private Connection conn;
private NodeInfoVO nodeInfoVO;
private InputStream stdOut = null;
private String charset = Charset.defaultCharset().toString();
private static final int TIME_OUT = 1000 * 5 * 60;
private static final Logger LOGGER = Logger.getLogger(SSHSession.class);
/**
* 构造函数
*
* @param nodeInfoVO
*/
public SSHSession(NodeInfoVO nodeInfoVO) {
this.nodeInfoVO = nodeInfoVO;
}
/**
* 登录
*
* @return
* @throws IOException
*/
private boolean login() throws IOException {
conn = new Connection(nodeInfoVO.getServerIp());
conn.connect();
return conn.authenticateWithPassword(nodeInfoVO.getServerUserName(), nodeInfoVO.getServerPassword());
}
/**
* 执行脚本
*
* @param cmds
* @return
* @throws Exception
*/
public String execCommand(String cmds) {
String outStr = "";
try {
if (login()) {
// Open a new {@link Session} on this connection
Session session = conn.openSession();
// Execute a command on the remote machine.
session.execCommand(cmds);
stdOut = new StreamGobbler(session.getStdout());
outStr = processStream(stdOut, charset);
session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
} else {
LOGGER.error("登录远程机器失败"); // 自定义异常类 实现略
}
} catch (Exception e) {
return outStr;
} finally {
close();
}
return outStr;
}
/**
* @param in
* @param charset
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
private String processStream(InputStream in, String charset) throws Exception {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
return sb.toString();
}
public static void main(String args[]) throws Exception {
SSHSession exe = new SSHSession(new ServerBean("10.10.5.219", 22, "root", "tt"));
System.out.println(exe.execCommand("ls "));
}
/**
* @return 获取 serverBean属性值
*/
public NodeInfoVO getNodeInfoVO() {
return nodeInfoVO;
}
/**
*
* @see com.comtop.numen.monitor.collection.appservice.device.remote.IRemoteSession#close()
*/
@Override
public void close() {
if (conn != null) {
conn.close();
}
IOUtils.closeQuietly(stdOut);
}