java获取主机cpu信息和磁盘容量
互联网中对主机的监控需求日益强烈,本人写一点监控windows和linux主机的cpu和磁盘信息,希望对各位有用。jdk版本是jdk5,jdk6有封装的方法,直接调用比较简单。以下是源代码:
package com.mcm.ucix.telnet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.StringTokenizer;
import com.mcm.ucix.telnet.Bytes;
?
?
/**
?* 监控主机CPU和HD类
?* @author fengbo? 2012-02-27
?*
?*/
public class MonitorCPUandHD
{
? public String host;/* 主机监控地址 */
?
? public String hostName ;
? public String hostIP ;
? public String name;/* 主机监控名称 */
? public int port;/* 主机监控端口 */??
? public int AllHDMeasure;/* 磁盘总空间*/
?
? private static final int CPUTIME = 30;
? private static final int PERCENT = 100;
? private static final int FAULTLENGTH = 10;
? private static String linuxVersion = null;
?
? /**
?? * 读取配置文件
?? * @param file
?? */
? public void loadConfigure(String file)
? {
???????? try
???????? {
???????????? InputStream conf = getClass().getResourceAsStream(file);
???????????? Properties props = new Properties();
???????????? props.load(conf);
???????????? conf.close();
?????????? //? host = props.getProperty("host");
???????? ??InetAddress addr;
???????? ??addr = InetAddress.getLocalHost();
???????? ??hostIP=addr.getHostAddress();//获得本机IP
???????? ??//String address=addr.getHostName();//获得本机名称
???????? ??
//???????????? String sport = props.getProperty("port");
//???????????? port = Integer.parseInt(sport);
//???????????? user = props.getProperty("user");
//???????????? pass = props.getProperty("pass");
???????????? AllHDMeasure = Integer.parseInt(props.getProperty("AllHDMeasure"));
???????? }
???????? catch (Exception ex)
???????? {
???????????? System.out.println("$_MCM_TELNET$ :" + ex.toString());
???????? }
?? }
?
? /**
?? * 读取磁盘剩余空间
?? * @param dirName
?? * @return
?? */
? public? long getFreeDiskSpace(String dirName)
??{
???try
???????? {??
//????String ip = host;?
//????int TCP_PORT = port;
//????Socket sct = new Socket(ip, TCP_PORT);
//???????????? System.out.println("连接成功");
//???????????? sct.getReuseAddress();
????????????
??????? String os = System.getProperty("os.name");
??????? String command;
??????? if (os.equals("Windows NT") ||os.equals("Windows XP"))
????????????? {
????????????????? command = "cmd.exe /c dir " + dirName;
??????? }
??????? else
??????? {
??????????? command = "command.com /c dir " + dirName;
??????? }
??????? Runtime runtime = Runtime.getRuntime();
??????? Process process = null;
??????? process = runtime.exec(command);
??????? if (process == null)
??????? {
??????????? return -1;
??????? }
???????
???? // read the output of the dir command
???? // only the last line is of interest
???????? BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
???????? String line;
???????? String freeSpace = null;
???????? while ((line = in.readLine()) != null)
???????? {
??????????? freeSpace = line;
???????? }
???????? if (freeSpace == null)
???????? {
?????? ?? return -1;
???????? }
???????? process.destroy();
????????
????? // remove dots & commas & leading and trailing whitespace
????????? freeSpace = freeSpace.trim();
????????? freeSpace = freeSpace.replaceAll("\\.", "");
????????? freeSpace = freeSpace.replaceAll(",", "");
????????? String[] items = freeSpace.split(" ");
????? // the first valid numeric value in items after(!) index 0
????? // is probably the free disk space
????????? int index = 1;
????????? while (index < items.length)
????????? {
????????????? try
??????????????????? {
????????????????? long bytes = Long.parseLong(items[index++]);
?????????????????
????????????????? //返回的大小是G。
????????????????? return bytes;
??????????????????? }
??????????????????? catch (NumberFormatException nfe)
????????????? {
???????????????? ??? //System.out.print("读取磁盘文件错误!");
????????????? }
??????????????? }
??????? return -1;
???}
???catch (Exception e )
???{
????return -1;
???}
??}
?
? /**
????? * 获取操作系统的使用率。
????? * @return
????? */
???? public double getCpuRatio()
???? {
???????? // 操作系统
???????? String osName = System.getProperty("os.name");
???????? double cpuRatio = 0;
???????? if (osName.toLowerCase().startsWith("windows"))
???????? {
???????? ?//获取windows操作系统图的cpu使用率。
???????????? cpuRatio = this.getCpuRatioForWindows();
???????? } else
???????? {
???????? ?//获取Linux操作系统图的cpu使用率。
???????????? cpuRatio = this.getCpuRateForLinux();
???????? }
???????? return cpuRatio;
???? }
???? /**
????? * 获得当前的监控对象.
????? *
????? * @return 返回构造好的监控对象
????? */
???? public MonitorInfoBean getMonitorInfoBean() throws Exception
???? {
???????? // 操作系统
???????? String osName = System.getProperty("os.name");
???????? // 获得线程总数
???????? ThreadGroup parentThread;
???????? for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
???????????????? .getParent() != null; parentThread = parentThread.getParent())
???????????? ;
???????? int totalThread = parentThread.activeCount();
???????? double cpuRatio = 0;
???????? if (osName.toLowerCase().startsWith("windows")) {
???????????? cpuRatio = this.getCpuRatioForWindows();
???????? } else {
???????????? cpuRatio = this.getCpuRateForLinux();
???????? }
???????? // 构造返回对象
???????? MonitorInfoBean infoBean = new MonitorInfoBean();
???????? infoBean.setTotalThread(totalThread);
???????? infoBean.setCpuRatio(cpuRatio);
???????? return infoBean;
???? }
???? /**
????? * 读取Linux下面的cpu信息。
????? * @return
????? */
???? private? double getCpuRateForLinux() {
???????? InputStream is = null;
???????? InputStreamReader isr = null;
???????? BufferedReader brStat = null;
???????? StringTokenizer tokenStat = null;
???????? try {
???????????? System.out.println("Get usage rate of CUP , linux version: "
???????????????????? + linuxVersion);
???????????? Process process = Runtime.getRuntime().exec("top -b -n 1");
???????????? is = process.getInputStream();
???????????? isr = new InputStreamReader(is);
???????????? brStat = new BufferedReader(isr);
???????????? if (linuxVersion.equals("2.4")) {
???????????????? brStat.readLine();
???????????????? brStat.readLine();
???????????????? brStat.readLine();
???????????????? brStat.readLine();
???????????????? tokenStat = new StringTokenizer(brStat.readLine());
???????????????? tokenStat.nextToken();
???????????????? tokenStat.nextToken();
???????????????? String user = tokenStat.nextToken();
???????????????? tokenStat.nextToken();
???????????????? String system = tokenStat.nextToken();
???????????????? tokenStat.nextToken();
???????????????? String nice = tokenStat.nextToken();
???????????????? System.out.println(user + " , " + system + " , " + nice);
???????????????? user = user.substring(0, user.indexOf("%"));
???????????????? system = system.substring(0, system.indexOf("%"));
???????????????? nice = nice.substring(0, nice.indexOf("%"));
???????????????? float userUsage = new Float(user).floatValue();
???????????????? float systemUsage = new Float(system).floatValue();
???????????????? float niceUsage = new Float(nice).floatValue();
???????????????? return (userUsage + systemUsage + niceUsage) / 100;
???????????? } else {
???????????????? brStat.readLine();
???????????????? brStat.readLine();
???????????????? tokenStat = new StringTokenizer(brStat.readLine());
???????????????? tokenStat.nextToken();
???????????????? tokenStat.nextToken();
???????????????? tokenStat.nextToken();
???????????????? tokenStat.nextToken();
???????????????? tokenStat.nextToken();
???????????????? tokenStat.nextToken();
???????????????? tokenStat.nextToken();
???????????????? String cpuUsage = tokenStat.nextToken();
???????????????? System.out.println("CPU idle : " + cpuUsage);
???????????????? Float usage = new Float(cpuUsage.substring(0, cpuUsage
???????????????????????? .indexOf("%")));
???????????????? return (1 - usage.floatValue() / 100);
???????????? }
???????? } catch (IOException ioe) {
???????????? System.out.println(ioe.getMessage());
???????????? freeResource(is, isr, brStat);
???????????? return 1;
???????? } finally {
???????????? freeResource(is, isr, brStat);
???????? }
???? }
???? private static void freeResource(InputStream is, InputStreamReader isr,
???????????? BufferedReader br) {
???????? try {
???????????? if (is != null)
???????????????? is.close();
???????????? if (isr != null)
???????????????? isr.close();
???????????? if (br != null)
???????????????? br.close();
???????? } catch (IOException ioe) {
???????????? System.out.println(ioe.getMessage());
???????? }
???? }
???? /**
????? * 获得CPU使用率.
????? *
????? * @return 返回cpu使用率
????? * @author fengbo 2012-02-27
????? */
???? private double getCpuRatioForWindows()
???? {
???????? try
???????? {
???????????? String procCmd = System.getenv("windir")
???????????????????? + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"
???????????????????? + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
???????????? // 取进程信息
???????????? long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
???????????? Thread.sleep(CPUTIME);
???????????? long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
???????????? if (c0 != null && c1 != null)
???????????? {
???????????????? long idletime = c1[0] - c0[0];
???????????????? long busytime = c1[1] - c0[1];
???????????????? return Double.valueOf(
???????????????????????? PERCENT * (busytime) / (busytime + idletime))
???????????????????????? .doubleValue();
???????????? }
???????????? else
???????????? {
???????????????? return 0.0;
???????????? }
???????? } catch (Exception ex)
???????? {
???????????? ex.printStackTrace();
???????????? return 0.0;
???????? }
???? }
???? /**
????? *
????? * 读取CPU信息.
????? *
????? * @param proc
????? * @author fengbo 2012-02-23
????? */
???? private long[] readCpu(final Process proc) {
???????? long[] retn = new long[2];
???????? try {
???????????? proc.getOutputStream().close();
???????????? InputStreamReader ir = new InputStreamReader(proc.getInputStream());
???????????? LineNumberReader input = new LineNumberReader(ir);
???????????? String line = input.readLine();
???????????? if (line == null || line.length() < FAULTLENGTH)
???????????? {
???????????????? return null;
???????????? }
???????????? int capidx = line.indexOf("Caption");
???????????? int cmdidx = line.indexOf("CommandLine");
???????????? int rocidx = line.indexOf("ReadOperationCount");
???????????? int umtidx = line.indexOf("UserModeTime");
???????????? int kmtidx = line.indexOf("KernelModeTime");
???????????? int wocidx = line.indexOf("WriteOperationCount");
???????????? long idletime = 0;
???????????? long kneltime = 0;
???????????? long usertime = 0;
???????????? while ((line = input.readLine()) != null) {
???????????????? if (line.length() < wocidx) {
???????????????????? continue;
???????????????? }
???????????????? String caption = Bytes.substring(line, capidx, cmdidx - 1)
???????????????????????? .trim();
???????????????? String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
???????????????? if (cmd.indexOf("wmic.exe") >= 0) {
???????????????????? continue;
???????????????? }
???????????????? if (caption.equals("System Idle Process")
???????????????????????? || caption.equals("System")) {
???????????????????? idletime += Long.valueOf(
???????????????????????????? Bytes.substring(line, kmtidx, rocidx - 1).trim())
???????????????????????????? .longValue();
???????????????????? idletime += Long.valueOf(
???????????????????????????? Bytes.substring(line, umtidx, wocidx - 1).trim())
???????????????????????????? .longValue();
???????????????????? continue;
???????????????? }
???????????????? kneltime += Long.valueOf(
???????????????????????? Bytes.substring(line, kmtidx, rocidx - 1).trim())
???????????????????????? .longValue();
???????????????? usertime += Long.valueOf(
???????????????????????? Bytes.substring(line, umtidx, wocidx - 1).trim())
???????????????????????? .longValue();
???????????? }
???????????? retn[0] = idletime;
???????????? retn[1] = kneltime + usertime;
???????????? return retn;
???????? } catch (Exception ex) {
???????????? ex.printStackTrace();
???????? } finally {
???????????? try {
???????????????? proc.getInputStream().close();
???????????? } catch (Exception e) {
???????????????? e.printStackTrace();
???????????? }
???????? }
???????? return null;
???? }
???? public static void main(String[] args) throws Exception
???? {
???? ?MonitorCPUandHD c = new MonitorCPUandHD();
???????? System.out.println("cpu占有率=" + c.getCpuRatio()+"%");
????????
???????? System.out.println("HD占用空间=" + c.getAllfreeHD()+"%");
??????
???? }
????
???? /**
????? * 获取HD总的剩余空间。单位是G
????? * @return
????? * @author fengbo 2012-02-27
????? */
???? public? long getAllfreeHD()
???? {
???? ?? Long allFreeDiskSpace = 0L;
??? ?? for (char c1 = 'A'; c1 <= 'Z'; c1++)
??????? {
??? ???? String dirName = c1 + ":\\";
??? ???? allFreeDiskSpace += getFreeDiskSpace(dirName);
??? ?? }
??? ? return allFreeDiskSpace/1024/1024/1024;
???? }
????
???? /**
????? * 获取磁盘利用率
????? * @author fengbo 2012-3-1
????? * @return
????? */
???? public double getAllHDRate()
???? {
???? ?//总空间数
//???? ?long resultAll = 0l;
//???? ?//已经使用的总数。
//???? ?long resultUsed = 0l;
//???? ?
//???? ?//使用率
//???? ?double hdUsedRate = 0.00;
//???? ?File [] file = File.listRoots();
//???? ?for (int i = 0; i<file.length; i++)
//???? ?{
//???? ??resultAll += file[i].getTotalSpace();
//???? ??resultUsed += file[i].getUsableSpace();
//???? ?}
//???? ?
//???? ?hdUsedRate = 100 * resultUsed / resultAll;
//???? ?return hdUsedRate;
???? ?return 0l;
???? }
????
????
????
????
/**
?* linux 下获取内存信息
?* @return
?* @throws IOException
?* @throws InterruptedException
?*/
???? public static int[] getMemInfo() throws IOException, InterruptedException
??{
???File file = new File("/proc/meminfo");
???BufferedReader br = new BufferedReader(new InputStreamReader(
?????new FileInputStream(file)));
???int[] result = new int[4];
???String str = null;
???StringTokenizer token = null;
???while ((str = br.readLine()) != null)
???{
????token = new StringTokenizer(str);
????if (!token.hasMoreTokens())
?????continue;
????str = token.nextToken();
????if (!token.hasMoreTokens())
?????continue;
????if (str.equalsIgnoreCase("MemTotal:"))
?????result[0] = Integer.parseInt(token.nextToken());
????else if (str.equalsIgnoreCase("MemFree:"))
?????result[1] = Integer.parseInt(token.nextToken());
????else if (str.equalsIgnoreCase("SwapTotal:"))
?????result[2] = Integer.parseInt(token.nextToken());
????else if (str.equalsIgnoreCase("SwapFree:"))
?????result[3] = Integer.parseInt(token.nextToken());
???}
???return result;
??}
????
???? /**
????? * linux下获取cpu利用率
????? * @return
????? * @throws IOException
????? * @throws InterruptedException
????? */
??public static float getCpuInfo() throws IOException, InterruptedException
??{
???File file = new File("/proc/stat");
???BufferedReader br = new BufferedReader(new InputStreamReader(
?????new FileInputStream(file)));
???StringTokenizer token = new StringTokenizer(br.readLine());
???token.nextToken();
???int user1 = Integer.parseInt(token.nextToken());
???int nice1 = Integer.parseInt(token.nextToken());
???int sys1 = Integer.parseInt(token.nextToken());
???int idle1 = Integer.parseInt(token.nextToken());
???Thread.sleep(1000);
???br = new BufferedReader(
?????new InputStreamReader(new FileInputStream(file)));
???token = new StringTokenizer(br.readLine());
???token.nextToken();
???int user2 = Integer.parseInt(token.nextToken());
???int nice2 = Integer.parseInt(token.nextToken());
???int sys2 = Integer.parseInt(token.nextToken());
???int idle2 = Integer.parseInt(token.nextToken());
???return (float) ((user2 + sys2 + nice2) - (user1 + sys1 + nice1))
?????/ (float) ((user2 + nice2 + sys2 + idle2) - (user1 + nice1
???????+ sys1 + idle1));
??}
??
??
??
?? public? long getFreeDiskSpaceForLinux(String command)
???{??
????try
????????? {??
???????? Runtime runtime = Runtime.getRuntime();
???????? Process process = null;
???????? process = runtime.exec(command);
???????? if (process == null)
???????? {
???????????? return -1;
???????? }
????????
????????? BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
????????? String line;
????????? String freeSpace = null;
????????? while ((line = in.readLine()) != null)
????????? {
??????? ?? if ("df -v".equals(command))
??????? ?? {
??????? ??? freeSpace += line;
??????? ?? }
??????? ?? else
??????? ?? {
??????? ??? freeSpace = line;
??????? ?? }
???????????
????????? }
????????? if (freeSpace == null)
????????? {
??????? ?? return -1;
????????? }
????????? process.destroy();
?????????
?????? // remove dots & commas & leading and trailing whitespace
?????????? freeSpace = freeSpace.trim();
?????????? freeSpace = freeSpace.replaceAll("\\.", "");
?????????? freeSpace = freeSpace.replaceAll(",", "");
?????????? String[] items = freeSpace.split(" ");
?????????? int index = 1;
?????????? while (index < items.length)
?????????? {
?????????????? try
???????????????????? {
?????????????????? long bytes = Long.parseLong(items[index++]);
??????????????????
?????????????????? //返回的大小是G。
?????????????????? return bytes;
???????????????????? }
???????????????????? catch (NumberFormatException nfe)
?????????????? {
????????????????? ??? //System.out.print("读取磁盘文件错误!");
?????????????? }
???????????????? }
???????? return -1;
????}
????catch (Exception e )
????{
?????return -1;
????}
???}
}
?
?