Java 开发 通过SSH命令 来获取host的CPU核数
需求环境是K8S+Docker+SpringBoot,在某个集群部署下,添加host,计算该集群下的所有Node的CPU和刚才添加的Node的CPU,判断是否满足license规则的CpuLimit
核心参考资料
https://www.cnblogs.com/xiaoliu66007/p/11084208.html
public static String runCommand(String host, String user, String password, String cmd) throws Exception {
Session session = connect(host,user,password);
String result = runCommand(session, cmd, CommonConstant.DEFAULT_CHARSET_UTF_8);
disconnect(session);
return result;
}
public static String runCommand(Session session, String cmd, String charset) throws MarsRuntimeException {
try {
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand(cmd);
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
channelExec.connect();
InputStream in = channelExec.getInputStream();
String characterSet = StringUtils.isBlank(charset) ? CommonConstant.DEFAULT_CHARSET_UTF_8 : charset;
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(characterSet)));
String line = null;
StringBuffer result = new StringBuffer();
while ((line = reader.readLine()) != null) {
result.append(line + "\n");
}
reader.close();
channelExec.disconnect();
return result.toString();
} catch (Exception e) {
throw new XXXException();
}
}
public static Session connect(String host, String user, String password) throws MarsRuntimeException {
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(user, host, 22);
// 如果服务器连接不上,则抛出异常
if (session == null) {
throw new XXXException();
}
// 设置登陆主机的密码
session.setPassword(password);
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
// 设置登陆超时时间
session.connect(5000);
} catch (Exception e) {
throw new XXXException();
}
return session;
}