package cn.xt.admin.core.util;
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;
public class ServerInfoUtil {
public static final String HE_SHELL="cat /proc/cpuinfo |grep \"processor\"|sort -u|wc -l";
public static final String CPU_MEM_SHELL = "top -b -n 1";
public static final String FILES_SHELL = "df -hl";
public static final String[] COMMANDS = {HE_SHELL,CPU_MEM_SHELL, FILES_SHELL};
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
/**
* 连接到指定的HOST
*
* @return isConnect
* @throws JSchException JSchException
*/
private static Session connect(String user, String passwd, String host) {
JSch jsch = new JSch();
Session session =null;
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 session;
}
/**
* 远程连接Linux 服务器 执行相关的命令
*
* @param commands 执行的脚本
* @param user 远程连接的用户名
* @param passwd 远程连接的密码
* @param host 远程连接的主机IP
* @return 最终命令返回信息
*/
public static Map<String, String> execCommands(String[] commands, String user, String passwd, String host) {
Session session = connect(user, passwd, host);
if (null == session) {
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());
channel.disconnect();
}
} 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
*
* @param commands 执行的脚本
* @return 执行结果信息
*/
public static Map<String, String> execLocalCommands(String[] commands) {
Runtime runtime = Runtime.getRuntime();
Map<String, String> map = new HashMap<>();
StringBuilder stringBuffer;
BufferedReader reader;
Process process;
for (String command : commands) {
stringBuffer = new StringBuilder();
try {
process = runtime.exec(command);
InputStream inputStream = process.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
String buf;
while ((buf = reader.readLine()) != null) {
//舍弃PID 进程信息
if (buf.contains("PID")) {
break;
}
stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
//每个命令存储自己返回数据-用于后续对返回数据进行处理
map.put(command, stringBuffer.toString());
}
return map;
}
/**
* 处理 shell 返回的信息
* <p>
* 具体处理过程以服务器返回数据格式为准
* 不同的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%st
if (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 {
String[] split = line.split(":")[1]
.replace("TOTAL", " ")
.replace("USED", " ")
.replace("FREE", " ")
.replace("BUFFERS", " ")
.replace(" ,", " ").trim().split("\\s+");
memStr += "总共:" + disposeUnit(split[0]) + "G" ;
} 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);
}
}else if (command.equals(HE_SHELL)) {
//处理系统核数信息
buffer.append("系统核数:" + commandResult);
}
}
return 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
*
* @param commandResult 处理系统磁盘状态shell执行结果
* @return 处理后的结果
*/
private static String disposeFilesSystem(String commandResult) {
System.out.println(commandResult);
String[] strings = commandResult.split(LINE_SEPARATOR);
// final String PATTERN_TEMPLATE = "([a-zA-Z0-9%_/]*)\\s";
int size = 0;
int used = 0;
int avail = 0;
for (int i = 0; i < strings.length; i++) {
if (i == 0) continue;
int temp = 0;
String[] split = strings[i].split("\\s+");
if (split.length < 6){
continue;
}
// System.out.println(split[1] + "--" +split[2] +"--"+ split[3]);
size += disposeUnit(split[1]);
used += disposeUnit(split[2]);
avail += disposeUnit(split[3]);
// System.out.println(size + "**" +used +"**"+ avail);
/*for (String s : strings[i].split("\\s+")) {
System.out.println(s);
if (temp == 0) {
temp++;
continue;
}
if (!s.trim().isEmpty()) {
if (temp == 1) {
size += disposeUnit(s);
temp++;
} else {
used += disposeUnit(s);
temp = 0;
}
}
}*/
}
return new StringBuilder().append("大小 ").append(size).append("G , 已使用").append(used).append("G ,空闲")
.append(size - used).append("G").toString();
}
/**
* 处理单位转换
* K/KB/M/T 最终转换为G 处理
*
* @param s 带单位的数据字符串
* @return 以G 为单位处理后的数值
*/
private static double disposeUnit(String s) {
if ("0".equals(s)){
return 0;
}
try {
s = s.toUpperCase();
String lastIndex = s.substring(s.length() - 1);
String num = s.substring(0, s.length() - 1);
double parseInt = Double.parseDouble(num);
// int parseInt = Integer.parseInt(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 0;
}
return 0;
}
public static void main(String[] args) {
String[] uatH = new String[]{"172.16.100.217" ,
"172.16.100.218" ,
"172.16.100.219" ,
"172.16.100.220"};
String[] beta = new String[]{
"10.0.186.73" ,
"10.0.186.74" ,
"10.0.186.75" ,
"10.0.186.76"};
String[] dev = new String[]{
"172.16.100.210",
"172.16.100.211" ,
"172.16.100.212" ,
"172.16.100.213" ,
"172.16.100.214" ,
"172.16.100.215" ,
"172.16.100.216"};
String[] h10 = new String[]{
"10.0.186.10" ,
"10.0.186.11" ,
"10.0.186.12" ,
"10.0.186.13" ,
"10.0.186.14" ,
"10.0.186.15" ,
"10.0.186.16" ,
"10.0.186.17" ,
"10.0.186.18" ,
"10.0.186.19"};
String[] pro = new String[]{
/*"10.0.186.30" ,
"10.0.186.31" ,
"10.0.186.32" ,
"10.0.186.33" ,
"10.0.186.34" ,
"10.0.186.35" ,
"10.0.186.36" ,
"10.0.186.37" ,
"10.0.186.38" ,
"10.0.186.39" ,
"10.0.186.40" ,
"10.0.186.41" ,
"10.0.186.42" ,
"10.0.186.43" ,
"10.0.186.44" ,
"10.0.186.45" ,
"10.0.186.46" ,
"10.0.186.47" ,
"10.0.186.48" ,
"10.0.186.49" ,
"10.0.186.50" ,
"10.0.186.51" ,
"10.0.186.52" ,*/
"10.0.186.53" ,
"10.0.186.54" ,
"10.0.186.55" ,
"10.0.186.56" ,
"10.0.186.57" ,
"10.0.186.58" ,
"10.0.186.59" ,
"10.0.186.60"};
for (String host: uatH){
Map<String, String> result = execCommands(COMMANDS, "root", "1234567890", host);
System.out.println(host);
System.out.println(disposeResultMessage(result));
}
/*Map<String, String> result = execCommands(COMMANDS, "root", "1234567890", "172.16.100.222");
System.out.println(disposeResultMessage(result));*/
}
}
运行结果
172.16.100.220
Filesystem Size Used Avail Use% Mounted on
/dev/sdg3 99G 2.4G 92G 3% /
tmpfs 190G 0 190G 0% /dev/shm
/dev/sdg1 488M 30M 433M 7% /boot
/dev/sdg8 57G 3.7G 51G 7% /home
/dev/sdg5 99G 2.2G 92G 3% /opt
/dev/sdg2 197G 198M 187G 1% /var/lib
/dev/sdg6 99G 5.3G 89G 6% /var/log
/dev/sda1 559G 155G 377G 30% /hadoop/disk1
/dev/sdb1 559G 152G 379G 29% /hadoop/disk2
cm_processes 190G 4.8M 190G 1% /var/run/cloudera-scm-agent/process
/dev/mapper/data-lv_data
1.1T 71M 1.1T 1% /data1
系统核数:40
内存使用情况:总共:378.4106788635254G
系统磁盘状态:大小 2049G , 已使用319G ,空闲1730G