Java method to get basic information about the server

  • 2020-04-01 04:03:21
  • OfStack

This article illustrates how Java can get basic information about a server. Share with you for your reference. The details are as follows:

Third party jars are used :(hyperic-hq official website: http://www.hyperic.com) to obtain server status data through the basic package of hyperic-hq products, sigar. Jar. The sigar.jar package is a local method to call the operating system API to get system-related data. Under Windows operating system, Sigar. Jar depends on sigar-amd64-winnt. DLL or sigar-x86-winnt. DLL, while under Linux operating system, it depends on libsigar-amd64-linux.so or libsigar-x86-linux.so


import java.net.InetAddress; 
import java.net.UnknownHostException; 
import org.hyperic.sigar.CpuInfo; 
import org.hyperic.sigar.CpuPerc; 
import org.hyperic.sigar.FileSystem; 
import org.hyperic.sigar.FileSystemUsage; 
import org.hyperic.sigar.Mem; 
import org.hyperic.sigar.NetFlags; 
import org.hyperic.sigar.NetInterfaceConfig; 
import org.hyperic.sigar.NetInterfaceStat; 
import org.hyperic.sigar.OperatingSystem; 
import org.hyperic.sigar.Sigar; 
import org.hyperic.sigar.SigarException; 
import org.hyperic.sigar.SigarNotImplementedException; 
import org.hyperic.sigar.Swap;
public class SysInfo {
// 1.CPU Resource information  // a)CPU Quantity (unit: unit)  
public static int getCpuCount() throws SigarException { 
 Sigar sigar = new Sigar(); 
 try { 
  return sigar.getCpuInfoList().length; 
 } finally { 
  sigar.close(); 
 } 
} //B) total amount of CPU (unit: HZ) and related information of CPU
public void getCpuTotal() { 
 Sigar sigar = new Sigar(); 
 CpuInfo[] infos; 
 try { 
  infos = sigar.getCpuInfoList(); 
  for (int i = 0; i < infos.length; i++) {//This applies to either a single block CPU or multiple cpus
  CpuInfo info = infos[i]; 
  System.out.println("mhz=" + info.getMhz());//The total amount of CPU is MHz
  System.out.println("vendor=" + info.getVendor());//Vendors that acquire cpus, such as Intel
  System.out.println("model=" + info.getModel());//Gets the CPU category, such as Celeron
  System.out.println("cache size=" + info.getCacheSize());//Buffer number
  } 
 } catch (SigarException e) { 
  e.printStackTrace(); 
 } 
} //C)CPU user usage, system residual, total residual, total usage, etc. (unit: 100%)
public void testCpuPerc() { 
 Sigar sigar = new Sigar(); 
 //Way one, mainly for a CPU
 CpuPerc cpu; 
 try { 
  cpu = sigar.getCpuPerc(); 
  printCpuPerc(cpu); 
 } catch (SigarException e) { 
  e.printStackTrace(); 
 } 
 //Method 2, whether it is a single CPU or multiple cpus
 CpuPerc cpuList[] = null; 
 try { 
  cpuList = sigar.getCpuPercList(); 
 } catch (SigarException e) { 
  e.printStackTrace(); 
  return; 
 } 
 for (int i = 0; i < cpuList.length; i++) { 
  printCpuPerc(cpuList[i]); 
 } 
} private void printCpuPerc(CpuPerc cpu) { 
 System.out.println("User :" + CpuPerc.format(cpu.getUser()));//User usage
 System.out.println("Sys :" + CpuPerc.format(cpu.getSys()));//System utilization
 System.out.println("Wait :" + CpuPerc.format(cpu.getWait()));//Current waiting rate
 System.out.println("Nice :" + CpuPerc.format(cpu.getNice()));// 
 System.out.println("Idle :" + CpuPerc.format(cpu.getIdle()));//Current idle rate
 System.out.println("Total :" + CpuPerc.format(cpu.getCombined()));//Total utilization rate
} //2. Memory resource information
public void getPhysicalMemory() { 
 //A) physical memory information
 Sigar sigar = new Sigar(); 
 Mem mem; 
 try { 
  mem = sigar.getMem(); 
  //Total memory
  System.out.println("Total = " + mem.getTotal() / 1024L + "K av"); 
  //Current memory usage
  System.out.println("Used = " + mem.getUsed() / 1024L + "K used"); 
  //Current memory surplus
  System.out.println("Free = " + mem.getFree() / 1024L + "K free");  //B) system page file exchange area information
  Swap swap = sigar.getSwap(); 
  //Total exchange area
  System.out.println("Total = " + swap.getTotal() / 1024L + "K av"); 
  //Current swap usage
  System.out.println("Used = " + swap.getUsed() / 1024L + "K used"); 
  //The amount remaining in the current swap
  System.out.println("Free = " + swap.getFree() / 1024L + "K free"); 
 } catch (SigarException e) { 
  e.printStackTrace(); 
 } 
} // 3. Operating system information  // a) Gets the name of the current operating system:  
public String getPlatformName() { 
 String hostname = ""; 
 try { 
  hostname = InetAddress.getLocalHost().getHostName(); 
 } catch (Exception exc) { 
  Sigar sigar = new Sigar(); 
  try { 
  hostname = sigar.getNetInfo().getHostName(); 
  } catch (SigarException e) { 
  hostname = "localhost.unknown"; 
  } finally { 
  sigar.close(); 
  } 
 } 
 return hostname; 
} //B) take the information of the current operating system
public void testGetOSInfo() { 
 OperatingSystem OS = OperatingSystem.getInstance(); 
 //Operating system kernel types such as x86 386, 486, 586, etc
 System.out.println("OS.getArch() = " + OS.getArch()); 
 System.out.println("OS.getCpuEndian() = " + OS.getCpuEndian());// 
 System.out.println("OS.getDataModel() = " + OS.getDataModel());// 
 //System description
 System.out.println("OS.getDescription() = " + OS.getDescription()); 
 System.out.println("OS.getMachine() = " + OS.getMachine());// 
 //Operating system type
 System.out.println("OS.getName() = " + OS.getName()); 
 System.out.println("OS.getPatchLevel() = " + OS.getPatchLevel());// 
 //Operating system vendors
 System.out.println("OS.getVendor() = " + OS.getVendor()); 
 //The vendor name
 System.out 
  .println("OS.getVendorCodeName() = " + OS.getVendorCodeName()); 
 //Operating system name
 System.out.println("OS.getVendorName() = " + OS.getVendorName()); 
 //Operating system vendor type
 System.out.println("OS.getVendorVersion() = " + OS.getVendorVersion()); 
 //Version number of the operating system
 System.out.println("OS.getVersion() = " + OS.getVersion()); 
} //C) take the user information in the current system process table
public void testWho() { 
 try { 
  Sigar sigar = new Sigar(); 
  org.hyperic.sigar.Who[] who = sigar.getWhoList(); 
  if (who != null && who.length > 0) { 
  for (int i = 0; i < who.length; i++) { 
   System.out.println("n~~~~~~~~~" + String.valueOf(i)+ "~~~~~~~~~"); 
   org.hyperic.sigar.Who _who = who[i]; 
   System.out.println("getDevice() = " + _who.getDevice()); 
   System.out.println("getHost() = " + _who.getHost()); 
   System.out.println("getTime() = " + _who.getTime()); 
   //The user name in the current system process table
   System.out.println("getUser() = " + _who.getUser()); 
  } 
  } 
 } catch (SigarException e) { 
  e.printStackTrace(); 
 } 
} // 4. Resource information (mainly hard disk)  // a) Take the existing partition of the hard disk and its details (via sigar.getFileSystemList() To obtain a FileSystem List the objects and then edit them) :  
public void testFileSystemInfo() throws Exception { 
 Sigar sigar = new Sigar(); 
 FileSystem fslist[] = sigar.getFileSystemList(); 
 //String dir = System.getProperty("user.home");//  Current user folder path  
 for (int i = 0; i < fslist.length; i++) { 
  System.out.println("n~~~~~~~~~~" + i + "~~~~~~~~~~"); 
  FileSystem fs = fslist[i]; 
  //The character name of the partition
  System.out.println("fs.getDevName() = " + fs.getDevName()); 
  //The character name of the partition
  System.out.println("fs.getDirName() = " + fs.getDirName()); 
  System.out.println("fs.getFlags() = " + fs.getFlags());// 
  //File system types, such as FAT32, NTFS
  System.out.println("fs.getSysTypeName() = " + fs.getSysTypeName()); 
  //File system type name, such as local hard disk, optical drive, network file system, and so on
  System.out.println("fs.getTypeName() = " + fs.getTypeName()); 
  //File system type
  System.out.println("fs.getType() = " + fs.getType()); 
  FileSystemUsage usage = null; 
  try { 
  usage = sigar.getFileSystemUsage(fs.getDirName()); 
  } catch (SigarException e) { 
  if (fs.getType() == 2) 
   throw e; 
  continue; 
  } 
  switch (fs.getType()) { 
  case 0: //Unknown TYPE_UNKNOWN:
  break; 
  case 1: // TYPE_NONE 
  break; 
  case 2: //TYPE_LOCAL_DISK: local hard disk
  //Total file system size
  System.out.println(" Total = " + usage.getTotal() + "KB"); 
  //File system residual size
  System.out.println(" Free = " + usage.getFree() + "KB"); 
  //Size of file system available
  System.out.println(" Avail = " + usage.getAvail() + "KB"); 
  //The file system has been used
  System.out.println(" Used = " + usage.getUsed() + "KB"); 
  double usePercent = usage.getUsePercent() * 100D; 
  //Utilization of file system resources
  System.out.println(" Usage = " + usePercent + "%"); 
  break; 
  case 3://TYPE_NETWORK: network
  break; 
  case 4://TYPE_RAM_DISK: flash memory
  break; 
  case 5://TYPE_CDROM: drive
  break; 
  case 6://TYPE_SWAP: page swap
  break; 
  } 
  System.out.println(" DiskReads = " + usage.getDiskReads()); 
  System.out.println(" DiskWrites = " + usage.getDiskWrites()); 
 } 
 return; 
} // 5. The network information  // a) The official domain name of the current machine  
public String getFQDN() { 
 Sigar sigar = null; 
 try { 
  return InetAddress.getLocalHost().getCanonicalHostName(); 
 } catch (UnknownHostException e) { 
  try { 
  sigar = new Sigar(); 
  return sigar.getFQDN(); 
  } catch (SigarException ex) { 
  return null; 
  } finally { 
  sigar.close(); 
  } 
 } 
} //B) get the IP address of the current machine
public String getDefaultIpAddress() { 
 String address = null; 
 try { 
  address = InetAddress.getLocalHost().getHostAddress(); 
  //There is no exception but normal when the IP is fetched, it will return if it is not the network card return address
  //Otherwise, it is obtained through methods in the Sigar toolkit
  if (!NetFlags.LOOPBACK_ADDRESS.equals(address)) { 
  return address; 
  } 
 } catch (UnknownHostException e) { 
  // hostname not in DNS or /etc/hosts 
 } 
 Sigar sigar = new Sigar(); 
 try { 
  address = sigar.getNetInterfaceConfig().getAddress(); 
 } catch (SigarException e) { 
  address = NetFlags.LOOPBACK_ADDRESS; 
 } finally { 
  sigar.close(); 
 } 
 return address; 
} //C) get the MAC address of the current machine
public String getMAC() { 
 Sigar sigar = null; 
 try { 
  sigar = new Sigar(); 
  String[] ifaces = sigar.getNetInterfaceList(); 
  String hwaddr = null; 
  for (int i = 0; i < ifaces.length; i++) { 
  NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]); 
  if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) 
   || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
   || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) { 
   continue; 
  } 
  
  hwaddr = cfg.getHwaddr(); 
  break; 
  } 
  return hwaddr != null  hwaddr : null; 
 } catch (Exception e) { 
  return null; 
 } finally { 
  if (sigar != null) 
  sigar.close(); 
 } 
} //D) access to network traffic and other information
public void testNetIfList() throws Exception { 
 Sigar sigar = new Sigar(); 
 String ifNames[] = sigar.getNetInterfaceList(); 
 for (int i = 0; i < ifNames.length; i++) { 
  String name = ifNames[i]; 
  NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name); 
  print("nname = " + name);//Network device name
  print("Address = " + ifconfig.getAddress());//The IP address
  print("Netmask = " + ifconfig.getNetmask());//Subnet mask
  if ((ifconfig.getFlags() & 1L) <= 0L) { 
  print("!IFF_UP...skipping getNetInterfaceStat"); 
  continue; 
  } 
  try { 
  NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name); 
  print("RxPackets = " + ifstat.getRxPackets());//Total number of packages received
  print("TxPackets = " + ifstat.getTxPackets());//Total number of packages sent
  print("RxBytes = " + ifstat.getRxBytes());//Total number of bytes received
  print("TxBytes = " + ifstat.getTxBytes());//Total number of bytes sent
  print("RxErrors = " + ifstat.getRxErrors());//Number of error packets received
  print("TxErrors = " + ifstat.getTxErrors());//Number of errors in sending packets
  print("RxDropped = " + ifstat.getRxDropped());//Number of packets dropped at reception
  print("TxDropped = " + ifstat.getTxDropped());//Number of packets dropped when sent
  } catch (SigarNotImplementedException e) { 
  } catch (SigarException e) { 
  print(e.getMessage()); 
  } 
 } 
} void print(String msg) { 
 System.out.println(msg); 
} //E) some other information
public void getEthernetInfo() { 
 Sigar sigar = null; 
 try { 
  sigar = new Sigar(); 
  String[] ifaces = sigar.getNetInterfaceList(); 
  for (int i = 0; i < ifaces.length; i++) { 
  NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]); 
  if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) 
   || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
   || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) { 
   continue; 
  } 
  System.out.println("cfg.getAddress() = " + cfg.getAddress());//The IP address
  System.out 
   .println("cfg.getBroadcast() = " + cfg.getBroadcast());//Gateway broadcast address
  System.out.println("cfg.getHwaddr() = " + cfg.getHwaddr());//Network card MAC address
  System.out.println("cfg.getNetmask() = " + cfg.getNetmask());//Subnet mask
  System.out.println("cfg.getDescription() = "
   + cfg.getDescription());//Network card description information
  System.out.println("cfg.getType() = " + cfg.getType());// 
  System.out.println("cfg.getDestination() = "
   + cfg.getDestination()); 
  System.out.println("cfg.getFlags() = " + cfg.getFlags());// 
  System.out.println("cfg.getMetric() = " + cfg.getMetric()); 
  System.out.println("cfg.getMtu() = " + cfg.getMtu()); 
  System.out.println("cfg.getName() = " + cfg.getName()); 
  System.out.println(); 
  } 
 } catch (Exception e) { 
  System.out.println("Error while creating GUID" + e); 
 } finally { 
  if (sigar != null) 
  sigar.close(); 
 } 
}
}

I hope this article has been helpful to your Java programming.


Related articles: