当前位置:   article > 正文

Java 连接远程Linux 服务器执行 shell 脚本查看 CPU、内存、硬盘信息_java代码获取其他服务器的cpu、内存、磁盘

java代码获取其他服务器的cpu、内存、磁盘

pom.xml jar 包支持

  1.    <dependency>
  2. <groupId>com.jcraft</groupId>
  3. <artifactId>jsch</artifactId>
  4. <version>0.1.53</version>
  5. </dependency>

 JAVA代码

  1. package test2;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.text.NumberFormat;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. import org.apache.commons.lang3.StringUtils;
  10. import com.jcraft.jsch.Channel;
  11. import com.jcraft.jsch.ChannelExec;
  12. import com.jcraft.jsch.JSch;
  13. import com.jcraft.jsch.JSchException;
  14. import com.jcraft.jsch.Session;
  15. /**
  16. * 远程调用Linux shell 命令
  17. *
  18. * @author wei.Li by 14-9-2.
  19. */
  20. public class CPUTest {
  21. public static final String DIR_NAME="/boot";
  22. public static final String CPU_MEM_SHELL = "top -b -n 1";
  23. public static final String FILES_SHELL = "df -hl";
  24. public static final String[] COMMANDS = {CPU_MEM_SHELL, FILES_SHELL};
  25. public static final String LINE_SEPARATOR = System.getProperty("line.separator");
  26. private static Session session;
  27. /**
  28. * 连接到指定的HOST
  29. *
  30. * @return isConnect
  31. * @throws JSchException JSchException
  32. */
  33. private static boolean connect(String user, String passwd, String host) {
  34. JSch jsch = new JSch();
  35. try {
  36. session = jsch.getSession(user, host, 22);
  37. session.setPassword(passwd);
  38. java.util.Properties config = new java.util.Properties();
  39. config.put("StrictHostKeyChecking", "no");
  40. session.setConfig(config);
  41. session.connect();
  42. } catch (JSchException e) {
  43. e.printStackTrace();
  44. System.out.println("connect error !");
  45. return false;
  46. }
  47. return true;
  48. }
  49. /**
  50. * 远程连接Linux 服务器 执行相关的命令
  51. *
  52. * @param commands 执行的脚本
  53. * @param user 远程连接的用户名
  54. * @param passwd 远程连接的密码
  55. * @param host 远程连接的主机IP
  56. * @return 最终命令返回信息
  57. */
  58. public static Map<String, String> runDistanceShell(String[] commands, String user, String passwd, String host) {
  59. if (!connect(user, passwd, host)) {
  60. return null;
  61. }
  62. Map<String, String> map = new HashMap<>();
  63. StringBuilder stringBuffer;
  64. BufferedReader reader = null;
  65. Channel channel = null;
  66. try {
  67. for (String command : commands) {
  68. stringBuffer = new StringBuilder();
  69. channel = session.openChannel("exec");
  70. ((ChannelExec) channel).setCommand(command);
  71. channel.setInputStream(null);
  72. ((ChannelExec) channel).setErrStream(System.err);
  73. channel.connect();
  74. InputStream in = channel.getInputStream();
  75. reader = new BufferedReader(new InputStreamReader(in));
  76. String buf;
  77. while ((buf = reader.readLine()) != null) {
  78. //舍弃PID 进程信息
  79. if (buf.contains("PID")) {
  80. break;
  81. }
  82. stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
  83. }
  84. //每个命令存储自己返回数据-用于后续对返回数据进行处理
  85. map.put(command, stringBuffer.toString());
  86. }
  87. } catch (IOException | JSchException e) {
  88. e.printStackTrace();
  89. } finally {
  90. try {
  91. if (reader != null) {
  92. reader.close();
  93. }
  94. } catch (IOException e) {
  95. e.printStackTrace();
  96. }
  97. if (channel != null) {
  98. channel.disconnect();
  99. }
  100. session.disconnect();
  101. }
  102. return map;
  103. }
  104. /**
  105. * 直接在本地执行 shell
  106. *
  107. * @param commands 执行的脚本
  108. * @return 执行结果信息
  109. */
  110. public static Map<String, String> runLocalShell(String[] commands) {
  111. Runtime runtime = Runtime.getRuntime();
  112. Map<String, String> map = new HashMap<>();
  113. StringBuilder stringBuffer;
  114. BufferedReader reader;
  115. Process process;
  116. for (String command : commands) {
  117. stringBuffer = new StringBuilder();
  118. try {
  119. process = runtime.exec(command);
  120. InputStream inputStream = process.getInputStream();
  121. reader = new BufferedReader(new InputStreamReader(inputStream));
  122. String buf;
  123. while ((buf = reader.readLine()) != null) {
  124. //舍弃PID 进程信息
  125. if (buf.contains("PID")) {
  126. break;
  127. }
  128. stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
  129. }
  130. } catch (IOException e) {
  131. e.printStackTrace();
  132. return null;
  133. }
  134. //每个命令存储自己返回数据-用于后续对返回数据进行处理
  135. map.put(command, stringBuffer.toString());
  136. }
  137. return map;
  138. }
  139. /**
  140. * 处理 shell 返回的信息
  141. * <p>
  142. * 具体处理过程以服务器返回数据格式为准
  143. * 不同的Linux 版本返回信息格式不同
  144. *
  145. * @param result shell 返回的信息
  146. * @return 最终处理后的信息
  147. */
  148. private static String disposeResultMessage(Map<String, String> result) {
  149. StringBuilder buffer = new StringBuilder();
  150. for (String command : COMMANDS) {
  151. String commandResult = result.get(command);
  152. if (null == commandResult) continue;
  153. if (command.equals(CPU_MEM_SHELL)) {
  154. String[] strings = commandResult.split(LINE_SEPARATOR);
  155. //将返回结果按换行符分割
  156. for (String line : strings) {
  157. line = line.toUpperCase();//转大写处理
  158. //处理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%st
  159. if (line.startsWith("CPU(S):")) {
  160. String cpuStr = "CPU 用户使用占有率:";
  161. try {
  162. cpuStr += line.split(":")[1].split(",")[0].replace("US", "");
  163. } catch (Exception e) {
  164. e.printStackTrace();
  165. cpuStr += "计算过程出错";
  166. }
  167. buffer.append(cpuStr).append(LINE_SEPARATOR);
  168. //处理内存 Mem: 66100704k total, 65323404k used, 777300k free, 89940k buffers
  169. } else if (line.startsWith("MEM")) {
  170. String memStr = "内存使用情况:";
  171. try {
  172. memStr += line.split(":")[1]
  173. .replace("TOTAL", "总计")
  174. .replace("USED", "已使用")
  175. .replace("FREE", "空闲")
  176. .replace("BUFFERS", "缓存");
  177. } catch (Exception e) {
  178. e.printStackTrace();
  179. memStr += "计算过程出错";
  180. buffer.append(memStr).append(LINE_SEPARATOR);
  181. continue;
  182. }
  183. buffer.append(memStr).append(LINE_SEPARATOR);
  184. }
  185. }
  186. } else if (command.equals(FILES_SHELL)) {
  187. //处理系统磁盘状态
  188. buffer.append("系统磁盘状态:");
  189. try {
  190. buffer.append(disposeFilesSystem(commandResult)).append(LINE_SEPARATOR);
  191. } catch (Exception e) {
  192. e.printStackTrace();
  193. buffer.append("计算过程出错").append(LINE_SEPARATOR);
  194. }
  195. }
  196. }
  197. return buffer.toString();
  198. }
  199. //处理系统磁盘状态
  200. /**
  201. * Filesystem Size Used Avail Use% Mounted on
  202. * /dev/sda3 442G 327G 93G 78% /
  203. * tmpfs 32G 0 32G 0% /dev/shm
  204. * /dev/sda1 788M 60M 689M 8% /boot
  205. * /dev/md0 1.9T 483G 1.4T 26% /ezsonar
  206. *
  207. * @param commandResult 处理系统磁盘状态shell执行结果
  208. * @return 处理后的结果
  209. */
  210. private static String disposeFilesSystem(String commandResult) {
  211. String[] strings = commandResult.split(LINE_SEPARATOR);
  212. // final String PATTERN_TEMPLATE = "([a-zA-Z0-9%_/]*)\\s";
  213. Double size = 0.0;
  214. Double used = 0.0;
  215. for (int i = 0; i < strings.length - 1; i++) {
  216. if (i == 0) continue;
  217. if(StringUtils.isNotBlank(DIR_NAME)){
  218. //不指定目录则查看所有内存使用
  219. if(!strings[i].endsWith(DIR_NAME)) continue;
  220. }
  221. int temp = 0;
  222. for (String s : strings[i].split(" +")) {
  223. // for (String s : strings[i].split("\\b")) {
  224. if (temp == 0) {
  225. temp++;
  226. continue;
  227. }
  228. if (!s.trim().isEmpty()) {
  229. if (temp == 1) {
  230. size += disposeUnit(s);
  231. temp++;
  232. } else {
  233. used += disposeUnit(s);
  234. temp = 0;
  235. }
  236. }
  237. }
  238. }
  239. String numPercent = getNumPercent(used,size);
  240. System.out.println("内存使用率:"+numPercent);
  241. return new StringBuilder().append("大小 ").append(size).append("G , 已使用").append(used).append("G ,空闲")
  242. .append(size - used).append("G").toString();
  243. }
  244. public static String getNumPercent(Double num1,Double num2){
  245. if(num2==0){
  246. return "0%";
  247. }
  248. // 创建一个数值格式化对象
  249. NumberFormat numberFormat = NumberFormat.getInstance();
  250. // 设置精确到小数点后2
  251. numberFormat.setMaximumFractionDigits(2);
  252. return numberFormat.format(num1 / num2 * 100)+ "%";
  253. }
  254. /**
  255. * 处理单位转换
  256. * K/KB/M/T 最终转换为G 处理
  257. *
  258. * @param s 带单位的数据字符串
  259. * @return 以G 为单位处理后的数值
  260. */
  261. private static double disposeUnit(String s) {
  262. try {
  263. s = s.toUpperCase();
  264. String lastIndex = s.substring(s.length() - 1);
  265. String num = s.substring(0, s.length() - 1);
  266. double parseInt = Double.parseDouble(num);
  267. if (lastIndex.equals("G")) {
  268. return parseInt;
  269. } else if (lastIndex.equals("T")) {
  270. return parseInt * 1024;
  271. } else if (lastIndex.equals("M")) {
  272. return parseInt / 1024;
  273. } else if (lastIndex.equals("K") || lastIndex.equals("KB")) {
  274. return parseInt / (1024 * 1024);
  275. }
  276. } catch (NumberFormatException e) {
  277. e.printStackTrace();
  278. return 0;
  279. }
  280. return 0;
  281. }
  282. public static void main(String[] args) {
  283. Map<String, String> result = runDistanceShell(COMMANDS, "root", "Netinfo@dev",
  284. "172.16.4.32");
  285. System.out.println(disposeResultMessage(result));
  286. }
  287. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/154160
推荐阅读
相关标签
  

闽ICP备14008679号