Java 连接远程Linux 服务器执行 shell 脚本查看 CPU、内存、硬盘
发布时间:2020-12-15 06:40:05 所属栏目:Java 来源:网络整理
导读:pom.xml jar 包支持 dependency groupId com.jcraft / artifactId jsch version 0.1.53 代码: package com.spring.bean.annotation; import java.io.BufferedReader; java.io.IOException; java.io.InputStream; java.io.InputStreamReader; java.util.Hash
pom.xml jar 包支持<dependency> <groupId>com.jcraft</artifactId>jschversion>0.1.53> > 代码: package com.spring.bean.annotation; import java.io.BufferedReader; java.io.IOException; java.io.InputStream; java.io.InputStreamReader; java.util.HashMap; java.util.Map; com.jcraft.jsch.Channel; com.jcraft.jsch.ChannelExec; com.jcraft.jsch.JSch; com.jcraft.jsch.JSchException; com.jcraft.jsch.Session; /** * 远程调用Linux shell 命令 * * @author wei.Li by 14-9-2. */ public class LinuxStateForShell { static final String CPU_MEM_SHELL = "top -b -n 1"; final String FILES_SHELL = "df -hl"final String[] COMMANDS = {CPU_MEM_SHELL,FILES_SHELL}; final String LINE_SEPARATOR = System.getProperty("line.separator"); private static Session session; * 连接到指定的HOST * * @return isConnect * @throws JSchException JSchException */ 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 = java.util.Properties(); config.put("StrictHostKeyChecking","no"); session.setConfig(config); session.connect(); } catch (JSchException e) { e.printStackTrace(); System.out.println("connect error !"); return false; } true; } * 远程连接Linux 服务器 执行相关的命令 * * @param commands 执行的脚本 * user 远程连接的用户名 * passwd 远程连接的密码 * host 远程连接的主机IP * 最终命令返回信息 static Map<String,String> runDistanceShell(String[] commands,String user,String host) { if (!connect(user,passwd,host)) { null; } Map<String,String> map = new HashMap<>(); StringBuilder stringBuffer; BufferedReader reader = ; Channel channel = ; { for (String command : commands) { stringBuffer = StringBuilder(); channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(); ((ChannelExec) channel).setErrStream(System.err); channel.connect(); InputStream in = channel.getInputStream(); reader = new BufferedReader( InputStreamReader(in)); String buf; while ((buf = reader.readLine()) != ) { //舍弃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 { if (reader != ) { reader.close(); } } (IOException e) { e.printStackTrace(); } if (channel != ) { channel.disconnect(); } session.disconnect(); } return map; } * 直接在本地执行 shell * * 执行结果信息 runLocalShell(String[] commands) { Runtime runtime = Runtime.getRuntime(); Map<String,1)">(); StringBuilder stringBuffer; BufferedReader reader; Process process; (String command : commands) { stringBuffer = StringBuilder(); { process = runtime.exec(command); InputStream inputStream = process.getInputStream(); reader = InputStreamReader(inputStream)); String buf; ) { ; } stringBuffer.append(buf.trim()).append(LINE_SEPARATOR); } } (IOException e) { e.printStackTrace(); ; } map.put(command,stringBuffer.toString()); } * 处理 shell 返回的信息 * <p> * 具体处理过程以服务器返回数据格式为准 * 不同的Linux 版本返回信息格式不同 * * result shell 返回的信息 * 最终处理后的信息 static String disposeResultMessage(Map<String,1)"> result) { StringBuilder buffer = StringBuilder(); (String command : COMMANDS) { String commandResult = result.get(command); if (null == commandResult) continue; if (command.equals(CPU_MEM_SHELL)) { String[] strings = commandResult.split(LINE_SEPARATOR); 将返回结果按换行符分割 (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%st if (line.startsWith("CPU(S):")) { String cpuStr = "CPU 用户使用占有率:"; { cpuStr += line.split(":")[1].split(",")[0].replace("US",""); } (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 = "内存使用情况:" { memStr += line.split(":")[1] .replace("TOTAL","总计") .replace("USED","已使用") .replace("FREE","空闲") .replace("BUFFERS","缓存"); } (Exception e) { e.printStackTrace(); memStr += "计算过程出错"; buffer.append(memStr).append(LINE_SEPARATOR); ; } buffer.append(memStr).append(LINE_SEPARATOR); } } } (command.equals(FILES_SHELL)) { 处理系统磁盘状态 buffer.append("系统磁盘状态:"); { buffer.append(disposeFilesSystem(commandResult)).append(LINE_SEPARATOR); } (Exception e) { e.printStackTrace(); buffer.append("计算过程出错").append(LINE_SEPARATOR); } } } buffer.toString(); } 处理系统磁盘状态 * Filesystem Size Used Avail Use% Mounted on * /dev/sda3 442G 327G 93G 78% / * tmpfs 32G 0 32G 0% /dev/shm * /dev/sda1 788M 60M 689M 8% /boot * /dev/md0 1.9T 483G 1.4T 26% /ezsonar * * commandResult 处理系统磁盘状态shell执行结果 * 处理后的结果 String disposeFilesSystem(String commandResult) { String[] strings = commandResult.split(LINE_SEPARATOR); final String PATTERN_TEMPLATE = "([a-zA-Z0-9%_/]*)s"; int size = 0int used = 0for (int i = 0; i < strings.length - 1; i++) { if (i == 0) int temp = 0; for (String s : strings[i].split("b")) { if (temp == 0) { temp++; ; } s.trim().isEmpty()) { if (temp == 1) { size += disposeUnit(s); temp++; } else { used += disposeUnit(s); temp = 0; } } } } new StringBuilder().append("大小 ").append(size).append("G,已使用").append(used).append("G,空闲") .append(size - used).append("G").toString(); } * 处理单位转换 * K/KB/M/T 最终转换为G 处理 * * s 带单位的数据字符串 * 以G 为单位处理后的数值 int disposeUnit(String s) { { s = s.toUpperCase(); String lastIndex = s.substring(s.length() - 1); String num = s.substring(0,s.length() - 1int parseInt = Integer.parseInt(num); if (lastIndex.equals("G" parseInt; } if (lastIndex.equals("T"return parseInt * 1024; } if (lastIndex.equals("M"return parseInt / 1024if (lastIndex.equals("K") || lastIndex.equals("KB"return parseInt / (1024 * 1024); } } (NumberFormatException e) { e.printStackTrace(); return 0void main(String[] args) { Map<String,String> result = runDistanceShell(COMMANDS,"dell","1","192.168.1.122"); System.out.println(disposeResultMessage(result)); } } ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |