【java获取到linux虚拟机的硬件信息–cpu信息、服务器名称、操作系统、ip地址等】
工作中遇到的接口
添加maven依赖
<!--shell脚本依赖-->
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
工具类:SSHToolUtil
package com.ph.server.myserver.util;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class SSHToolUtil {
private Connection conn;
private String ipAddr;
private Charset charset = StandardCharsets.UTF_8;
private String userName;
private String password;
public SSHToolUtil(String ipAddr, String userName, String password) {
this.ipAddr = ipAddr;
this.userName = userName;
this.password = password;
if (charset != null) {
this.charset = charset;
}
}
/**
* 登录远程Linux主机
*
* @return 是否登录成功
*/
private boolean login() {
conn = new Connection(ipAddr);
try {
// System.out.println("登录");
// 连接
conn.connect();
// 认证
return conn.authenticateWithPassword(userName, password);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 执行Shell脚本或命令
*
* @param cmds 命令行序列
* @return 脚本输出结果
*/
public StringBuilder exec(String cmds) throws IOException {
InputStream in = null;
StringBuilder result = new StringBuilder();
try {
if (this.login()) {
// System.out.println("333");
// 打开一个会话
Session session = conn.openSession();
session.execCommand(cmds);
in = session.getStdout();
result = this.processStdout(in, this.charset);
conn.close();
}
} finally {
if (null != in) {
in.close();
}
}
return result;
}
/**
* 解析流获取字符串信息
*
* @param in 输入流对象
* @param charset 字符集
* @return 脚本输出结果
*/
public StringBuilder processStdout(InputStream in, Charset charset) throws FileNotFoundException {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
// OutputStream os = new FileOutputStream("./data.txt");
try {
int length;
while ((length = in.read(buf)) != -1) {
// os.write(buf, 0, c);
sb.append(new String(buf, 0, length));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb;
}
}
scontroller层调用(为了方便,逻辑直接写在里面了)
package com.ph.server.myserver.controller;
import com.ph.server.myserver.model.AjaxObj;
import com.ph.server.myserver.model.Linux;
import com.ph.server.myserver.util.SSHToolUtil;
import com.ph.server.myserver.value.ReturnValCode;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@RestController
@CrossOrigin(allowCredentials = "true", origins = "*", maxAge = 3600)
@RequestMapping("/linux")
public class GetLinuxMegController {
private SSHToolUtil tool;
/**
* 获取虚拟机数据
*/
@RequestMapping(value = "/getlinux",method = {RequestMethod.GET,RequestMethod.POST})
public AjaxObj getlinux(String ipAddr, String userName, String password){
Linux linux=new Linux();
tool = new SSHToolUtil(ipAddr, userName, password);
try {
// cpu核数
StringBuilder exec = tool.exec("cat /proc/cpuinfo |grep \"cores\"|uniq");
String cpuString = exec.toString().trim();
String reg = "[^0-9]";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(cpuString);
int cpuInt = 0;
try {
cpuInt = (Integer.parseInt(matcher.replaceAll("").trim()));
String cpu = String.valueOf(cpuInt * 2) + "核";
linux.setCpu(cpu);
} catch (NumberFormatException e) {
e.printStackTrace();
linux.setCpu("暂未获取到数据");
System.out.println("数据异常或命令行错误");
}
// 服务器名称
StringBuilder hostname1 = tool.exec("hostname");
String hostname = null;
try {
hostname = hostname1.toString().trim();
linux.setHostname(hostname);
} catch (Exception e) {
e.printStackTrace();
linux.setHostname("暂未获取到数据");
System.out.println("数据异常或命令行错误");
}
// 操作系统
StringBuilder system1 = tool.exec("cat /etc/redhat-release");
String system = null;
try {
system = system1.toString().trim();
linux.setSystem(system);
} catch (Exception e) {
e.printStackTrace();
linux.setSystem("暂未获取到数据");
System.out.println("数据异常或命令行错误");
}
// ip地址
StringBuilder ip1 = tool.exec("ifconfig |awk -F \"[ :]+\" 'NR==2{print $3}'");
String ip = null;
try {
ip = ip1.toString().trim();
linux.setIp(ip);
} catch (Exception e) {
e.printStackTrace();
linux.setIp("暂未获取到数据");
System.out.println("数据异常或命令行错误");
}
// cpu内存
StringBuilder memtotal = tool.exec(" cat /proc/meminfo | grep MemTotal\n");
String trim = memtotal.toString().trim();
String regEx="[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(trim);
int parseInt = 0;
try {
parseInt = (Integer.parseInt(m.replaceAll("").trim()))/100000;
String cpuMemory = String.valueOf(parseInt)+"G";
linux.setCpuMemory(cpuMemory);
} catch (NumberFormatException e) {
e.printStackTrace();
linux.setCpuMemory("暂未获取到数据");
System.out.println("数据转换异常或命令行错误");
}
// 硬盘容量
StringBuilder yingpan = tool.exec(" smartctl --all /dev/sda |awk -F \"[ :]+\" 'NR==8{print $5}'");
String handSize = null;
try {
handSize = yingpan.substring(1,yingpan.length()).trim()+"G";
linux.setHandSize(handSize);
} catch (Exception e) {
e.printStackTrace();
linux.setHandSize("暂未获取到数据");
System.out.println("数据转换异常或命令行错误");
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("IP地址或用户名或密码错误");
}
return new AjaxObj(ReturnValCode.RTN_VAL_CODE_SUCCESS, "请求成功",linux);
}
}
更复杂的逻辑
package com.ph.server.myserver.controller;
import com.ph.server.myserver.model.AjaxObj;
import com.ph.server.myserver.model.Linux;
import com.ph.server.myserver.util.CommUtils;
import com.ph.server.myserver.util.SSHToolUtil;
import com.ph.server.myserver.value.ReturnValCode;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@RestController
@CrossOrigin(allowCredentials = "true", origins = "*", maxAge = 3600)
@RequestMapping("/linux")
public class GetLinuxMegController {
private SSHToolUtil tool;
/**
* 获取虚拟机数据
*/
@RequestMapping(value = "/getlinux",method = {RequestMethod.GET,RequestMethod.POST})
public AjaxObj getlinux(String ipAddr, String userName, String password){
Linux linux=new Linux();
tool = new SSHToolUtil(ipAddr, userName, password);
try {
// 每个物理cpu核数
StringBuilder exec = tool.exec("cat /proc/cpuinfo |grep \"cores\"|uniq");
// 物理cpu个数
StringBuilder count = tool.exec("cat /proc/cpuinfo| grep \"physical id\"| sort| uniq| wc -l");
int cpuNum = Integer.parseInt(count.toString().trim());
String cpuString = exec.toString().trim();
String reg = "[^0-9]";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(cpuString);
int cpuInt = 0;
try {
cpuInt = (Integer.parseInt(matcher.replaceAll("").trim()));
// 总核数 = 每颗物理CPU的核数 x 物理CPU个数
String cpu = String.valueOf(cpuInt * cpuNum) + "核";
linux.setCpu(cpu);
} catch (NumberFormatException e) {
e.printStackTrace();
linux.setCpu("暂未获取到数据");
System.out.println("数据异常或命令行错误");
}
// 服务器名称
StringBuilder hostname1 = tool.exec("hostname");
String hostname = null;
try {
hostname = hostname1.toString().trim();
linux.setHostname(hostname);
} catch (Exception e) {
e.printStackTrace();
linux.setHostname("暂未获取到数据");
System.out.println("数据异常或命令行错误");
}
// 操作系统
StringBuilder system1 = tool.exec("cat /etc/redhat-release");
String system = null;
try {
system = system1.toString().trim();
linux.setSystem(system);
} catch (Exception e) {
e.printStackTrace();
linux.setSystem("暂未获取到数据");
System.out.println("数据异常或命令行错误");
}
// ip地址
StringBuilder ip1 = tool.exec("ifconfig |awk -F \"[ :]+\" 'NR==2{print $3}'");
String ip = null;
try {
ip = ip1.toString().trim();
if(CommUtils.isEmpty(ip)){
linux.setIp(ipAddr);
}else{
linux.setIp(ip);
}
} catch (Exception e) {
e.printStackTrace();
linux.setIp("暂未获取到数据");
System.out.println("数据异常或命令行错误");
}
// cpu内存
StringBuilder memtotal = tool.exec("cat /proc/meminfo | grep MemTotal");
String trim = memtotal.toString().trim();
String regEx="[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(trim);
DecimalFormat de = new DecimalFormat("0.0");
double parseInt = 0;
try {
parseInt =(Double.parseDouble(m.replaceAll("").trim()))/1000000;
String format = de.format(parseInt);
String cpuMemory = String.valueOf(format)+"G";
linux.setCpuMemory(cpuMemory);
} catch (NumberFormatException e) {
e.printStackTrace();
linux.setCpuMemory("暂未获取到数据");
System.out.println("数据转换异常或命令行错误");
}
// 从linux获取总容量,已使用,未使用,使用率,先获取硬盘总容量,再获取已使用的,然后相除
StringBuilder fileSystem = tool.exec("df -h");
String fileSystemToString = fileSystem.toString();
BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(fileSystemToString.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
String line = null;
Integer number=1;
List list=new ArrayList();
while((line = br.readLine())!=null){
list.add(line);
}
br.close();
double g1=0;
double g2=0;
double g3=0;
double g4=0;
for (int i = 1; i < list.size(); i++) {
String replaceAll = list.get(i).toString().replaceAll("\r", "");
String[] s = replaceAll.split("\\s+|\n");
if(s[1].endsWith("M")){
String[] gs1 = s[1].split("M");
NumberFormat nf=new DecimalFormat( "0.0 ");
g1 = Double.parseDouble(gs1[0]);
g1=g1/1000;
g1 = (double) Math.round(g1 * 100) / 100;
}else if(s[1].endsWith("G")){
String[] gs1 = s[1].split("G");
g1 = Double.parseDouble(gs1[0]);
}else if(s[1].endsWith("K")){
String[] gs1 = s[1].split("K");
g1 = Double.parseDouble(gs1[0]);
g1=g1/1000;
g1 = (double) Math.round(g1 * 100) / 100;
g1=g1/1000;
g1 = (double) Math.round(g1 * 100) / 100;
}else if(s[1].endsWith("T")){
String[] gs1 = s[1].split("T");
g1 = Double.parseDouble(gs1[0]);
g1=g1*1024;
g1 = (double) Math.round(g1 * 100) / 100;
}else if("0".equals(s[1])){
g1=0;
}
if(s[2].endsWith("M")){
String[] gs1 = s[2].split("M");
g2 = Double.parseDouble(gs1[0]);
g2=g2/1000;
g2 = (double) Math.round(g2 * 100) / 100;
}else if(s[2].endsWith("G")){
String[] gs1 = s[2].split("G");
g2 = Double.parseDouble(gs1[0]);
}else if(s[2].endsWith("K")){
String[] gs1 = s[2].split("K");
g2 = Double.parseDouble(gs1[0]);
g2=g2/1000;
g2 = (double) Math.round(g2 * 100) / 100;
g2=g2/1000;
g2 = (double) Math.round(g2 * 100) / 100;
}else if(s[2].endsWith("T")){
String[] gs1 = s[2].split("T");
g2 = Double.parseDouble(gs1[0]);
g2=g2*1024;
g2 = (double) Math.round(g2 * 100) / 100;
}else if("0".equals(s[2])){
g2=0;
}
g3=g3+g1;
g4=g4+g2;
}
DecimalFormat df = new DecimalFormat("0");
String size = df.format(Math.round(g3));
String used = df.format(Math.round(g4));
String sum = df.format(Math.round((Float.parseFloat(used) / Float.parseFloat(size)) * 100));
linux.setHandSize("硬盘大小:"+size+"G/已使用:"+used+"G/使用率:"+sum+"%");
} catch (IOException e) {
e.printStackTrace();
System.out.println("IP地址或用户名或密码错误");
}
return new AjaxObj(ReturnValCode.RTN_VAL_CODE_SUCCESS, "请求成功",linux);
}
}
return是个对象,可以不写其他的,仅供参考