pom.xml jar 包支持<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.53</version></dependency>

注意点:不同版本的Linux 执行的命令返回的数据是不一样的 具体问题还得具体分析

package com.learn.service;
import com.jcraft.jsch.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;/*** 远程调用Linux shell 命令* @author yuyihao 2019.10.12*/
public class LinuxStateForShell {public static final String CPU_MEM_SHELL = "top -b -n 1"; // liunx 命令用戶獲取系統信息public static final String FILES_SHELL = "df -hl"; // 查看磁盘占用情况public static final String[] COMMANDS = {CPU_MEM_SHELL, FILES_SHELL}; // 命令數組/*** 在java中存在一些转义字符,比如"\n"为换行符, JDK自带的一些操作符  System.getProperty("line.separator");* 这也是换行符,功能和"\n"是一致的,用此方法能区分 Windows和Linux环境的换行。* 开发中与不是同一个环境,可以用 System.getProperty("line.separator");  来控制换行*/public static final String LINE_SEPARATOR = System.getProperty("line.separator");private static Session session;/*** 连接到指定的HOST* @return isConnect* @throws JSchException JSchException*/private static boolean connect(String user, String passwd, String host) {JSch jsch = new JSch();try {session = jsch.getSession(user, host, 22);session.setPassword(passwd);java.util.Properties config = new java.util.Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config);session.connect();} catch (JSchException e) {e.printStackTrace();System.out.println("connect error !");return false;}return true;}/*** 远程连接Linux 服务器 执行相关的命令* @param commands 执行的脚本* @param user     远程连接的用户名* @param passwd   远程连接的密码* @param host     远程连接的主机IP* @return 最终命令返回信息*/public static Map<String, String> runDistanceShell(String[] commands, String user, String passwd, String host) throws IOException {if (!connect(user, passwd, host)) {return null;}Map<String, String> map = new HashMap<>();StringBuilder stringBuffer;BufferedReader reader = null;Channel channel = null;try {for (String command : commands) {stringBuffer = new StringBuilder();channel = session.openChannel("exec");((ChannelExec) channel).setCommand(command);channel.setInputStream(null);((ChannelExec) channel).setErrStream(System.err);channel.connect();InputStream in = channel.getInputStream();reader = new BufferedReader(new InputStreamReader(in));String buf;while ((buf = reader.readLine()) != null) {//舍弃PID 进程信息if (buf.contains("PID")) {break;}stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);}//每个命令存储自己返回数据-用于后续对返回数据进行处理map.put(command, stringBuffer.toString());}} catch (IOException | JSchException e) {e.printStackTrace();} finally {try {if (reader != null) {reader.close();}} catch (IOException e) {e.printStackTrace();}if (channel != null) {channel.disconnect();}session.disconnect();}return map;}/*** 处理 shell 返回的信息* 具体处理过程以服务器返回数据格式为准* 不同的Linux 版本返回信息格式不同* @param result shell 返回的信息* @return 最终处理后的信息*/private static String disposeResultMessage(Map<String, String> result) {StringBuilder buffer = new StringBuilder();for (String command : COMMANDS) {String commandResult = result.get(command);if (null == commandResult) continue;if (command.equals(CPU_MEM_SHELL)) {String[] strings = commandResult.split(LINE_SEPARATOR);//将返回结果按换行符分割for (String line : strings) {line = line.toUpperCase();//转大写处理//处理CPU Cpu(s): 10.8%us,  0.9%sy,  0.0%ni, 87.6%id,  0.7%wa,  0.0%hi,  0.0%si,  0.0%stif (line.startsWith("CPU(S):")) {  //有的不带% 有的带- 此处是不带的系统String cpuStr = "CPU 用户使用占有率:";try {cpuStr += line.split(":")[1].split(",")[0].replace("US", "");} catch (Exception e) {e.printStackTrace();cpuStr += "计算过程出错";}buffer.append(cpuStr).append(LINE_SEPARATOR);//处理内存 Mem:  66100704k total, 65323404k used,   777300k free,    89940k buffers} else if (line.startsWith("MEM")) {String memStr = "内存使用情况:";try {memStr += line.split(":")[1].replace("TOTAL", "总计").replace("USED", "已使用").replace("FREE", "空闲").replace("BUFFERS", "缓存");} catch (Exception e) {e.printStackTrace();memStr += "计算过程出错";buffer.append(memStr).append(LINE_SEPARATOR);continue;}buffer.append(memStr).append(LINE_SEPARATOR);}}} else if (command.equals(FILES_SHELL)) {//处理系统磁盘状态buffer.append("系统磁盘状态:");try {buffer.append(disposeFilesSystem(commandResult)).append(LINE_SEPARATOR);} catch (Exception e) {e.printStackTrace();buffer.append("计算过程出错").append(LINE_SEPARATOR);}}}return buffer.toString();}//处理系统磁盘状态/*** @param commandResult 处理系统磁盘状态shell执行结果* @return 处理后的结果*//*** 最终处理的结果* CPU 用户使用占有率:  0.2%* 内存使用情况:   1020344K 总计,   160248K 已使用,   860096K 空闲,    14176K 缓存* 系统磁盘状态:大小 7.66G , 已使用2.93G ,空闲4.73G*/private static String disposeFilesSystem(String commandResult) {String[] strings = commandResult.split(LINE_SEPARATOR);// final String PATTERN_TEMPLATE = "([a-zA-Z0-9%_/]*)\\s";Double size = 0d;Double used = 0d;for (int i = 1; i < strings.length; i++) {//第一行 标题不需要String[] row = strings[i].split("\\s+");size += disposeUnit(row[1]); // 第二列 sizeused += disposeUnit(row[2]); // 第三列 used}return new StringBuilder().append("大小 ").append(Math.round(size * 100)/100d).append("G , 已使用").append(Math.round(used * 100)/100d).append("G ,空闲").append(Math.round((size - used) * 100)/100d).append("G").toString();}/*** 处理单位转换* K/KB/M/T 最终转换为G 处理* @param s 带单位的数据字符串* @return 以G 为单位处理后的数值*/private static Double disposeUnit(String s) {try {s = s.toUpperCase();String lastIndex = s.substring(s.length() - 1);String num = s.substring(0, s.length() - 1);Double parseInt = Double.parseDouble(num);if (lastIndex.equals("G")) {return parseInt;} else if (lastIndex.equals("T")) {return parseInt * 1024;} else if (lastIndex.equals("M")) {return parseInt / 1024;} else if (lastIndex.equals("K") || lastIndex.equals("KB")) {return parseInt / (1024 * 1024);}} catch (NumberFormatException e) {e.printStackTrace();return 0d;}return 0d;}public static void main(String[] args) throws IOException {Map<String, String> result = runDistanceShell(COMMANDS, "root", "root123", "192.168.56.101");System.out.println(disposeResultMessage(result));}}

JAVA端收集Liunx服务器 CPU 内存 磁盘使用率相关推荐

  1. AIX和LINUX主机 CPU 内存 磁盘使用率监控

    AIX监控 磁盘使用率监控 df -g|grep -v Filesystem|grep -v proc|awk ' gsub(/%/,"",$4) {print $7 " ...

  2. 脚本监控windows的cpu 内存 磁盘 使用率

    监控cpu使用率的vbs脚本, cpu.vbs(注意cpu0代表第一个cpu) On Error Resume Next Set objProc = GetObject("winmgmts: ...

  3. golang 获取cpu 内存 硬盘 使用率 信息 进程信息

    目录 1.获取 cpu 内存 磁盘使用率 2.获取本机信息 3. 获取CPU信息 4. 获取内存信息 5.获取磁盘信息 6.获取网络信息 7. 获取进程信息 使用库: go get github.co ...

  4. amd服务器和intel服务器性能,服务器CPU内存性能哪家强?AMD or Intel?

    原标题:服务器CPU内存性能哪家强?AMD or Intel? 基准配置和方法 MCT的一位导师在EPYC 7601.Skylake, 和Cascade Lake machines上进行了一项测试. ...

  5. 用python监控磁盘_使用python怎么对服务器cpu和磁盘空间进行监控

    使用python怎么对服务器cpu和磁盘空间进行监控 发布时间:2021-01-29 17:16:55 来源:亿速云 阅读:82 作者:Leah 这期内容当中小编将会给大家带来有关使用python怎么 ...

  6. 一个用了统计CPU 内存 硬盘 使用率的shell脚本

    一个用了统计CPU 内存 硬盘 使用率的shell脚本 一个统计 CPU 内存 硬盘 使用率的shell脚本,供大家学习参考 代码如下: #!/bin/bash #This script is use ...

  7. 如何评估服务器基础性能 - CPU负载、使用率、内存磁盘使用率、网络带宽......

    文章目录 关注服务硬软指标 服务器关键指标 CPU 负载 CPU 使用率 网卡 IN & OUT 内存 & 磁盘 Q&A 附录 关注服务硬软指标 在搭建维护服务时,我们经常和服 ...

  8. Linux 查看CPU 内存 IO使用率,linux 查看CPU内存 网络 流量 磁盘 IO

    使用vmstat命令来察看系统资源情况 在命令行方式下,如何查看CPU.内存的使用情况,网络流量和磁盘I/O? Q: 在命令行方式下,如何查看CPU.内存的使用情况,网络流量和磁盘I/O? A: 在命 ...

  9. FreeBSD 查看服务器 cpu 内存使用情况

    最近在公司接到一个freebsd的项目,主要是移植,中间涉及到freebsd中查看cpu占用率,内存的使用率等,查了一下,使用vmstat命令,粘贴一个博文:http://www.demix.cn/h ...

  10. 处理器仿存带宽_linux服务器CPU内存硬盘读写带宽等性能测试方法

    如何对一个VPS主机进行CPU内存,硬盘IO读写,带宽速度等项目测试,像UnixBench和压力测试则可以综合反映一个VPS的性能水平,方便大家对照参考. VPS性能测试:CPU内存,硬盘IO读写,带 ...

最新文章

  1. Android编译笔记之五
  2. centos7python命令_02.将python3作为centos7的默认python命令
  3. java控制系统音量_Java 控制 Windows 系统音量-Go语言中文社区
  4. IO对象流(序列化和反序列化)
  5. Gridiew——表的内容居中
  6. 1,2,3……,9组成3个三位数abc,def和ghi,每个数字恰好使用一次,要求abc:def:ghi=1:2:3.输出所有解。
  7. windows下用pip安装软件超时解决方案
  8. 八、关于FFmpeg需要絮叨的一些事
  9. PHP解密小程序加密信息
  10. 从阿里云迁移域名至 Amazon Route 53 帮你了解域名迁移
  11. android 发音乐通知到通知栏
  12. 生成MT/MTd模式的tet.lib
  13. Android布局原理与优化
  14. mysql 投影运算_数据库查询 - 通俗易懂解释:选择、投影、并、差、笛卡尔积、连接 - 小黑电脑...
  15. 编程自学网站(赶紧收藏)
  16. 关于Linux的应用层定时器
  17. Windows下的Program Files (x86)文件夹是干什么的?
  18. 领导者/追随者(Leader/Follower)
  19. 重庆大学计算机非全学费,重庆大学非全日制研究生学费多少,为什么非全日制研究生学费这么贵?...
  20. 微软公司招聘题目——狗的问题

热门文章

  1. 军团指挥官(权限题)
  2. 渥太华大学计算机学硕录取过程,西农计算机拟录取名单公布,初试第一被刷,289分倒数第一上岸...
  3. 马云选择了西雅图模式,你家公司选硅谷还是西雅图?
  4. 【软件】Excel文件双击打开巨慢,先开excel程序,将表格拖进来就很快,夜神模拟器导致开excel很慢
  5. C# 短消息提示 窗口位置
  6. LeetCode #1088. Confusing Number II
  7. Dapper基础入门
  8. 拷贝(添加)本地音乐到iPhone、iPad设备(最新iTunes12.7)
  9. android音乐播放器——通过webview下载歌曲
  10. 程序员是做全栈工程师好?还是专注一个领域好?