遠端採集伺服器指標資訊(一) 遠端通過SSH執行命令
阿新 • • 發佈:2019-02-13
遠端採集伺服器資訊,比如說磁碟資訊、記憶體資訊。
現介紹java通過SSH執行命令採集伺服器資訊,比如說執行df、ls、top。
/** * * 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); }