Java 开发 通过SSH命令 来获取host的CPU核数

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;
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值