/**
* Get system information
*
* @author cwg
* @version 1.0
* @date January 20, 2025
**/
public class SystemInfoProviderUtil {
/**
* Get system information
* Call the corresponding system information provider according to the operating system type (Windows or Linux).
*
* @param host host address
* @param user user name
* @param password
* @param port port number
* @return SystemInfo object, containing system information
*/
public static SystemInfo getSystemInfo(String host, String user, String password, int port, String serverType) {
SystemInfo systemInfo = new SystemInfo();
try {
// Different systems and different commands
if (("windows")) {
systemInfo = WindowsSystemInfoProvider(host, user, password, port);
} else if (("linux")) {
systemInfo = LinuxSystemInfoProvider(host, user, password, port);
}
(serverType);
} catch (Exception e) {
throw new RuntimeException(e);
}
return systemInfo;
}
/**
* window system
**/
private static SystemInfo WindowsSystemInfoProvider(String host, String user, String password, int port) throws Exception {
SystemInfo systemInfo = new SystemInfo();
JSch jsch = new JSch();
Session session = (user, host, port);
(password);
("StrictHostKeyChecking", "no");
();
// Execute the command
String cpuCommand = "wmic cpu get loadpercentage";
String memoryCommand = "wmic os get freephysicalmemory,totalvisiblememorysize";
String diskCommand = "wmic logicaldisk get size,freespace,caption";
String serviceCommand1 = "sc query WinSyncService";
String serviceCommand2 = "sc query GSessiond";
String timeCommand = "wmic os get localdatetime";
// Get CPU usage
String cpuUsageResult = executeCommand(session, cpuCommand);
// Extract all numbers and convert them into integers
String[] cpuUsageArray = ("[^\\d]", " ").trim().split("\\s+");
// Calculate the average CPU usage rate
int totalCpuUsage = 0;
int coreCount = ;
for (String cpuLoad : cpuUsageArray) {
totalCpuUsage += (cpuLoad);
}
// Calculate the average usage rate
int averageCpuUsage = totalCpuUsage / coreCount;
// Set system CPU usage rate
(averageCpuUsage);
(("[\r\n]", "").trim());
// Get memory information
String memoryInfo = executeCommand(session, memoryCommand);
(("[\r\n]", ""));
String[] memLines = ("\n");
if ( > 2) {
String freeMemory = memLines[2].split("\\s+")[0].trim();
String totalMemory = memLines[2].split("\\s+")[1].trim();
String usedMemory = ((totalMemory) - (freeMemory));
long usedMemoryPercentage = (long) (((usedMemory) / (totalMemory)) * 100);
(new BigDecimal(formatMemory(totalMemory).replaceAll("GB", "")));
(new BigDecimal(formatMemory(freeMemory).replaceAll("GB", "")));
(new BigDecimal(formatMemory(usedMemory).replaceAll("GB", "")));
(usedMemoryPercentage);
}
// Initialize storage of C disk disk information
long diskUsage = 0;
BigDecimal diskAvailableMemory = ;
// Get disk information
StringBuilder diskInfo = new StringBuilder(executeCommand(session, diskCommand));
(().trim());
String[] lines = ().split("\n");
if ( > 1) {
for (String lineInfo : lines) {
if (!().isEmpty()) {
String[] parts = ("\\s+");
if ( == 3) {
String drive = parts[0]; // Drive letter
String freeSpace = parts[1]; // Free space
String totalSpace = parts[2]; // Total space
if (!isInteger(freeSpace) || !isInteger(totalSpace)) {
diskInfo = new StringBuilder();
continue;
}
long usedSpace = (totalSpace) - (freeSpace); // Used space
long diskUsagePercentage = (long) (((((usedSpace)) / (totalSpace)) * 100);
(("Drive %s Total Space = %s, Available Space = %s, Used Space = %s, Disk Usage = %d%%\n",
drive, formatDiskSpace(totalSpace), formatDiskSpace(freeSpace), formatDiskSpace((usedSpace)), diskUsagePercentage));
if (("C")) {
diskUsage = diskUsagePercentage;
long freeSpaceLong = (freeSpace);
// Set disk usage and available space for disk C
String freeSpaceDouble = formatDiskSpace((freeSpaceLong));
diskAvailableMemory = new BigDecimal(("GB", ""));
}
}
}
}
}
(().trim());
(diskUsage);
(diskAvailableMemory);
// Get service status
String serviceStatus1 = executeCommand(session, serviceCommand1);
(("RUNNING"));
(("[\r\n]", ""));
String serviceStatus2 = executeCommand(session, serviceCommand2);
(("RUNNING"));
(("[\r\n]", ""));
// Get the current time
String currentTime = executeCommand(session, timeCommand);
String[] timeParts = ("\n");
if ( > 1) {
String dateTime = timeParts[2].trim();
currentTime = ("%s-%s-%s %s:%s:%s",
(0, 4), (4, 6), (6, 8),
(8, 10), (10, 12), (12, 14));
(currentTime);
}
();
return systemInfo;
}
/**
* Determine whether it is a number
*
* @param str
* @return
*/
public static boolean isInteger(String str) {
if (str == null || ()) {
return false;
}
try {
// Try to convert the string to a long type
(str);
return true;
} catch (NumberFormatException e) {
// If the conversion fails, it means that the string is not a valid long type number.
return false;
}
}
/**
* Linux system
**/
private static SystemInfo LinuxSystemInfoProvider(String host, String user, String password, int port) throws Exception {
SystemInfo systemInfo = new SystemInfo();
JSch jsch = new JSch();
Session session = (user, host, port);
(password);
("StrictHostKeyChecking", "no");
();
// Execute the command
String cpuCommand = "top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}'";
String memoryCommand = "free -m";
String diskCommand = "df -h";
String serviceCommand1 = "systemctl status WinSyncService";
String serviceCommand2 = "systemctl status GSessiond";
String timeCommand = "date";
String dfCommand = "df -h /";
// Get CPU usage
String cpuUsageResult = executeCommand(session, cpuCommand);
double cpuUsage = (());
((int) cpuUsage);
(());
// Get memory information
String memoryInfo = executeCommand(session, memoryCommand);
(("[\r\n]", ""));
List<String> memLines = splitLines(memoryInfo);
if (() > 1) {
String[] parts = (1).split("\\s+");
String totalMemory = parts[1];
String usedMemory = parts[2];
String freeMemory = parts[3];
//Memory usage = (Memory used / Total memory) * 100.
long usedMemoryPercentage = (long) (((usedMemory) / (totalMemory)) * 100);
(new BigDecimal(formatMemory(totalMemory).replaceAll("GB", "")));
(new BigDecimal(formatMemory(freeMemory).replaceAll("GB", "")));
(new BigDecimal(formatMemory(usedMemory).replaceAll("GB", "")));
(usedMemoryPercentage);
}
// Get disk information
StringBuilder diskInfo = new StringBuilder(executeCommand(session, diskCommand));
//Get the root directory information of the disk
StringBuilder diskInfogen = new StringBuilder(executeCommand(session, dfCommand));
List<String> strings = splitLines(());
if (() > 1) {
for (int i = 1; i < (); i++) {
String lineInfo = (i);
String[] parts = ("\\s+");
if ( >= 5) {
String availableSpace = parts[3];
((parts[4]));
(((availableSpace)));
(("root disk usage = %s, free space of root disk = %s\n",
parts[4], availableSpace));
}
}
}
(().trim());
List<String> diskLines = splitLines(());
if (() > 1) {
for (int i = 1; i < (); i++) {
String lineInfo = (i);
String[] parts = ("\\s+");
if ( >= 4) {
String drive = parts[0];
String totalSpace = parts[1];
String usedSpace = parts[2];
String availableSpace = parts[3];
(("Drive %s Total Space = %s, Available Space = %s, Used Space = %s\n",
drive, totalSpace, availableSpace, usedSpace));
}
}
}
(().trim());
// Get service status
String serviceStatus1 = executeCommand(session, serviceCommand1);
(("active (running)"));
(("[\r\n]", ""));
String serviceStatus2 = executeCommand(session, serviceCommand2);
(("active (running)"));
(("[\r\n]", ""));
// Get the current time
String currentTime = executeCommand(session, timeCommand);
(());
();
return systemInfo;
}
// Helpful method for executing commands
private static String executeCommand(Session session, String command) throws Exception {
StringBuilder result = new StringBuilder();
ChannelExec channel = (ChannelExec) ("exec");
(command);
();
InputStream inputStream = ();
();
// Use UTF-8 encoding to read the input stream (you can try other encodings, such as "GBK" if you want)
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
String line;
while ((line = ()) != null) {
(line).append("\n");
}
();
return ();
}
// Convert disk space from bytes to GB
private static String formatDiskSpace(String spaceInBytes) {
if (spaceInBytes == null || ()) {
return "0.00GB";
}
try {
long space = (spaceInBytes);
return ("%.2fGB", space / (1024.0 * 1024 * 1024)); // Return GB in a unified way
} catch (NumberFormatException e) {
return spaceInBytes; // If parsing fails, return the original value
}
}
// Convert memory size from KB to GB
private static String formatMemory(String memoryInKb) {
try {
long memory = (memoryInKb);
return ("%.2fGB", memory / (1024.0 * 1024)); // Unified return GB
} catch (NumberFormatException e) {
return memoryInKb; // If parsing fails, return the original value
}
}
// Split multiple lines of text
private static List<String> splitLines(String input) {
List<String> lines = new ArrayList<>();
String[] parts = ("\n");
for (String part : parts) {
(part);
}
return lines;
}
}
//entity
@Data
@ToString
public class SystemInfo {
//cpu usage rate
private int cpuUsage;
//Cpu query source returns result
private String cpuCommandResult;
//Total memory
private BigDecimal totalMemory;
//Available memory
private BigDecimal availableMemory;
// Memory has been used
private BigDecimal usedMemory;
//Memory usage
private long memoryUsageRate;
//The memory query source returns the result
private String memoryCommandResult;
//Disk information source returns result
private String diskInfoResult;
//Disk information
private String diskInfo;
//WinSync Service survival status
private boolean winSyncServiceRunning;
//WinSync Service survival status source returns the result
private String winSyncServiceCommandResult;
//GSessiond Service Survival status
private boolean gSessionServiceRunning;
//GSessiond service Live status source returns result
private String gSessionServiceCommandResult;
//Current time
private String currentTime;
//Disk usage rate WindowsC disk or linux root directory /
private long diskUsage;
//Available space
private BigDecimal diskAvailableMemory;
//Type linux || window
private String type;
}