Java实现 利用sigar.jar监控检测cpu、磁盘、内存的性能值查询和使用量查询 。以及根据进程名查询PID,根据PID杀死进程

Java实现 利用sigar.jar监控检测cpu、磁盘、内存的性能值查询和使用量查询 。以及根据进程名查询PID,根据PID杀死进程

import com.sun.jna.Library;
import com.sun.jna.Native;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import com.sun.jna.Platform;
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.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Swap;
import org.springframework.util.StringUtils;

public class GetInfo {

	public interface Kernel32 extends Library {
		public static Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);

		public long GetProcessId(Long hProcess);
	}

	/**
	 * 1.获取cpu信息
	 */
	public static void getCpuInfo() {
		System.out.println("***********获取cpu信息***********");
		Sigar sigar = new Sigar();
		// CPU的总量(单位:HZ)及CPU的相关信息
		CpuInfo infos[];
		try {
			// CPU数量(单位:个)
			System.out.println("核心cpu数:" + Runtime.getRuntime().availableProcessors());// 核心cpu数
			int cpuLength = sigar.getCpuInfoList().length;
			System.out.println("CPU数量" + cpuLength);
			infos = sigar.getCpuInfoList();

			for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
				CpuInfo info = infos[i];
				System.out.println("第" + i + 1 + "块");
				System.out.println("CPU的总量MHzmhz=" + info.getMhz());// CPU的总量MHz
				System.out.println("获得CPU的卖主,如:Intelvendor=" + info.getVendor());// 获得CPU的卖主,如:Intel
				System.out.println("获得CPU的类别,如:Celeronmodel=" + info.getModel());// 获得CPU的类别,如:Celeron
				System.out.println("缓冲存储器数量cache size=" + info.getCacheSize());// 缓冲存储器数量
			}
		} catch (SigarException e1) {
			e1.printStackTrace();
		}
		// 不管是单块CPU还是多CPU都适用
		CpuPerc cpuList[] = null;
		try {
			cpuList = sigar.getCpuPercList();
		} catch (SigarException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < cpuList.length; i++) {
			getCpuUsage(cpuList[i], i);
		}
	}

	/**
	 * 2.cpu使用率
	 * 
	 * @param cpu
	 */
	public static void getCpuUsage(CpuPerc cpu, int i) {
		System.out.println("***********获取cpu【" + (i + 1) + "】使用率***********");

		System.out.println("CPU用户使用率:    " + CpuPerc.format(cpu.getUser()));// 用户使用率
		System.out.println("CPU系统使用率:    " + CpuPerc.format(cpu.getSys()));// 系统使用率
		System.out.println("CPU当前等待率:    " + CpuPerc.format(cpu.getWait()));// 当前等待率
		System.out.println("CPU当前错误率:    " + CpuPerc.format(cpu.getNice()));//
		System.out.println("CPU当前空闲率:    " + CpuPerc.format(cpu.getIdle()));// 当前空闲率
		System.out.println("CPU总的使用率:    " + CpuPerc.format(cpu.getCombined()));// 总的使用率

	}

	/**
	 * 3.获取磁盘信息
	 * 
	 * @throws SigarException
	 */
	public static void getDiskInfo() throws SigarException {
		System.out.println("***********获取磁盘信息***********");
		// 取硬盘已有的分区及其详细信息(通过sigar.getFileSystemList()来获得FileSystem列表对象,然后对其进行编历
		Sigar sigar = new Sigar();
		FileSystem fslist[] = sigar.getFileSystemList();
		String dir = System.getProperty("user.home");// 当前用户文件夹路径
		System.out.println(dir + "   " + fslist.length);
		for (int i = 0; i < fslist.length; i++) {
			System.out.println("\n~~~~~~~~~~" + i + "~~~~~~~~~~");
			FileSystem fs = fslist[i];
			// 分区的盘符名称
			System.out.println("分区的盘符名称fs.getDevName() = " + fs.getDevName());
			// 分区的盘符名称
			System.out.println("分区的盘符名称fs.getDirName() = " + fs.getDirName());
			System.out.println("fs.getFlags() = " + fs.getFlags());//
			// 文件系统类型,比如 FAT32、NTFS
			System.out.println("文件系统类型,比如 FAT32、NTFSfs.getSysTypeName() = " + fs.getSysTypeName());
			// 文件系统类型名,比如本地硬盘、光驱、网络文件系统等
			System.out.println("文件系统类型名,比如本地硬盘、光驱、网络文件系统等fs.getTypeName() = " + fs.getTypeName());
			// 文件系统类型
			System.out.println("文件系统类型fs.getType() = " + fs.getType());

		}
	}

	/**
	 * 4.获取磁盘使用量
	 * 
	 * @throws SigarException
	 */
	public static void getDiskUsage() throws SigarException {
		System.out.println("***********获取磁盘使用量***********");
		Sigar sigar = new Sigar();
		FileSystem fslist[] = sigar.getFileSystemList();
		for (int i = 0; i < fslist.length; i++) {
			System.out.println("\n~~~~~~~~~~" + i + "~~~~~~~~~~");
			FileSystem fs = fslist[i];
			FileSystemUsage usage = null;
			try {
				usage = sigar.getFileSystemUsage(fs.getDirName());
			} catch (SigarException e) {
				if (fs.getType() == 2)
					throw e;
				continue;
			}
			switch (fs.getType()) {
			case 0: // TYPE_UNKNOWN :未知
				break;
			case 1: // TYPE_NONE
				break;
			case 2: // TYPE_LOCAL_DISK : 本地硬盘
				// 文件系统总大小
				System.out.println(" 文件系统总大小Total = " + usage.getTotal() + "KB");// diskTotal
				// 文件系统剩余大小
				System.out.println(" 文件系统剩余大小Free = " + usage.getFree() + "KB");
				// 文件系统可用大小
				System.out.println("  文件系统可用大小Avail = " + usage.getAvail() + "KB");
				// 文件系统已经使用量
				System.out.println(" 文件系统已经使用量Used = " + usage.getUsed() + "KB");// diskUsage
				double usePercent = usage.getUsePercent() * 100D;
				// 文件系统资源的利用率
				System.out.println(" 文件系统资源的利用率Usage = " + usePercent + "%");
				break;
			case 3:// TYPE_NETWORK :网络
				break;
			case 4:// TYPE_RAM_DISK :闪存
				break;
			case 5:// TYPE_CDROM :光驱
				break;
			case 6:// TYPE_SWAP :页面交换
				break;
			}
			System.out.println(" DiskReads = " + usage.getDiskReads());
			System.out.println(" DiskWrites = " + usage.getDiskWrites());

		}

	}

	/**
	 * 5.获取内存信息
	 * 
	 * @return
	 * @throws SigarException
	 */
	public static void getMemoryInfo() throws SigarException {
		System.out.println("***********获取内存信息***********");
		Sigar sigar = new Sigar();
		// 物理内存信息
		Mem mem = sigar.getMem();
		// 内存总量
		System.out.println("内存总量Total = " + mem.getTotal() / 1024L / 1024 + "M av");// memoryTotal;
		// 当前内存使用量
		System.out.println("当前内存使用量Used = " + mem.getUsed() / 1024L / 1024 + "M used");// memoryUsage
		// 当前内存剩余量
		System.out.println("当前内存剩余量Free = " + mem.getFree() / 1024L / 1024 + "M free");

		// 系统页面文件交换区信息
		Swap swap = sigar.getSwap();
		// 交换区总量
		System.out.println("交换区总量Total = " + swap.getTotal() / 1024L + "K av");
		// 当前交换区使用量
		System.out.println("当前交换区使用量Used = " + swap.getUsed() / 1024L + "K used");
		// 当前交换区剩余量
		System.out.println("当前交换区剩余量Free = " + swap.getFree() / 1024L + "K free");
	}

	/**
	 * 6.ServerSystemInfoVO填充属性
	 * 
	 * @param svo
	 * @return
	 * @throws SigarException
	 */
	public static ServerSystemInfoVO setServerSystemInfoVO(ServerSystemInfoVO svo) throws SigarException {
		Sigar sigar = new Sigar();
		Mem mem = sigar.getMem();
		FileSystem fslist[] = sigar.getFileSystemList();
		// 磁盘大小
		long diskTotal = 0;// b
		for (int i = 0; i < fslist.length; i++) {
			FileSystem fs = fslist[i];
			FileSystemUsage usage = null;
			try {
				usage = sigar.getFileSystemUsage(fs.getDirName());
				if (fs.getType() == 2) {
					diskTotal += usage.getTotal() * 1024;

				}
				String host = System.getProperty("java.rmi.server.hostname");
				svo.setIp((host == null || host.length() == 0) ? InetAddress.getLocalHost().getHostAddress() : host);
				svo.setCpuCoreCount(Runtime.getRuntime().availableProcessors());
				svo.setCpuCount(sigar.getCpuInfoList().length);
				svo.setDiskTotal(diskTotal);
				svo.setMemoryTotal(mem.getTotal());

			} catch (SigarException e) {
				if (fs.getType() == 2)
					throw e;
				continue;
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}

		}
		return svo;

	}

	/**
	 * 7.ServerResourceVO填充属性
	 * 
	 * @param svo
	 * @return
	 */
	public static ServerResourceVO setServerResourceVO(ServerResourceVO svo) {
		Sigar sigar = new Sigar();
		float cpuLoad = 0;
		try {
			Mem mem = sigar.getMem();
			double cputotal = 0;
			double Combinedtotal = 0;
			CpuPerc cpuList[] = sigar.getCpuPercList();
			for (int i = 0; i < cpuList.length; i++) {
				CpuPerc cpu = cpuList[i];
				Combinedtotal += cpu.getCombined();
				cputotal += 1;
			}
			cpuLoad = (float) (Combinedtotal / cputotal);
			long memoryUsage = mem.getUsed(); // b

			FileSystem fslist[] = sigar.getFileSystemList();
			// 磁盘使用量
			long diskUsage = 0;// b
			for (int i = 0; i < fslist.length; i++) {
				FileSystem fs = fslist[i];
				FileSystemUsage usage = null;
				try {
					usage = sigar.getFileSystemUsage(fs.getDirName());
					if (fs.getType() == 2) {
						diskUsage += usage.getUsed() * 1024;
					}
				} catch (SigarException e) {
					if (fs.getType() == 2)
						throw e;
					continue;
				}

			}
			String host = System.getProperty("java.rmi.server.hostname");
			Date date = new Date();
			svo.setIp((host == null || host.length() == 0) ? InetAddress.getLocalHost().getHostAddress() : host);
			svo.setCpuLoad(cpuLoad);
			svo.setDiskUsage(diskUsage);
			svo.setMemoryUsage(memoryUsage);
			svo.setTimestamp(date.getTime());
		} catch (SigarException e1) {
			e1.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

		return svo;

	}

	/**
	 * 根据进程名称找出进程的PID windows下ok linux下还没测试
	 * 
	 * @param processName 进程名
	 */
	public static void findExecuterProcess(String processName) {

		try {
			Process process = null;
			if (Platform.isWindows()) {
				String[] cmmd = { "cmd", "/c",
						"FOR /F \"tokens=2,3*\"; %i  in ('tasklist /nh ^| find \"" + processName + "\"') do @echo %i" };
				process = Runtime.getRuntime().exec(cmmd);
			} else if (Platform.isLinux() || Platform.isAIX()) {
				String cmmd = "ps -ef | grep \"" + processName + "\" | grep -v grep | awk '{print $2}'";
				process = Runtime.getRuntime().exec(cmmd);
			}
			String str = null;
			BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			while ((str = br.readLine()) != null) {
				// str就是PID
				System.out.println(str);
			}

		} catch (IOException e) {

			e.printStackTrace();
		}

	}

	/**
	 * 关闭Linux/windows进程
	 * 
	 * @param pid 进程的PID
	 */
	public static boolean killProcessByPid(String pid) {
		if (StringUtils.isEmpty(pid) || "-1".equals(pid)) {
			throw new RuntimeException("Pid ==" + pid);
		}
		Process process = null;
		BufferedReader reader = null;
		String command = "";
		boolean result = false;
		if (Platform.isWindows()) {
			command = "cmd.exe /c taskkill /PID " + pid + " /F /T ";
		} else if (Platform.isLinux() || Platform.isAIX()) {
			command = "kill -9 " + pid;
		}
		try {
			// 杀掉进程
			process = Runtime.getRuntime().exec(command);
			reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println("kill PID return info -----> " + line);

			}
			result = true;
		} catch (Exception e) {

			result = false;
		} finally {
			if (process != null) {
				process.destroy();
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {

				}
			}
		}
		return result;
	}

	public static void main(String[] args) throws SigarException {

		/*
		 * getCpuInfo(); getDiskInfo(); getMemoryInfo(); getDiskUsage();
		 * ServerSystemInfoVO svo = new ServerSystemInfoVO();
		 * System.out.println(setServerSystemInfoVO(svo));
		 * System.out.println(setServerResourceVO(new ServerResourceVO()));
		 */
		findExecuterProcess("Notepad.exe");
		// killProcessByPid("42100");
	}

}

posted @ 2021-12-08 16:39  剑心空明  阅读(24)  评论(0编辑  收藏  举报  来源