借助于 Hyperic-Sigar,是一个收集系统各项底层信息的工具集。没啥技术含量。

 参考:https://support.hyperic.com/display/SIGAR/Home

 下载地址:http://sourceforge.net/projects/sigar/files/sigar/1.6/hyperic-sigar-1.6.4.zip/download

解压后将hyperic-sigar-1.6.4\\sigar-bin\\lib 下所需的文件拷贝到项目lib下,里面包含两个jar包 和一些其他文件,不同的操作系统使用不同的文件,直接拷贝全部省事。

 Maven 依赖信息

代码 

<dependency>  

    <groupId>org.fusesource</groupId>  

    <artifactId>sigar</artifactId>  

    <version>1.6.4</version>  

</dependency>  

不多说,直接上代码(Spring MVC的 Controller), 返回json数据,前台页面可灵活调用显示

Java代码 

import java.io.IOException;  

import java.io.PrintWriter;  

import javax.servlet.http.HttpServletResponse;  

import org.apache.commons.logging.Log;  

import org.apache.commons.logging.LogFactory;  


/** 

 * @author 

 * 

 */  

public class  Controller {  

      
    protected Log logger = LogFactory.getLog(getClass());  

  
    protected void response2Client (HttpServletResponse response, String content) {  

          
        response.setContentType(\"text/html;charset=UTF-8\");  

        PrintWriter out = null;  
        

        logger.info(\"response content -->\" + content);  
         

        try {  

            out = response.getWriter();  

            out.print(content);  

            out.close();  

        } catch (IOException e) {  

            e.printStackTrace();  

        }  
          
    }    

}  

 

Java代码 

 

import java.net.InetAddress;  

import java.net.UnknownHostException;  

import java.util.Map;  

import java.util.Properties;    

import javax.servlet.http.HttpServletResponse;   

import net.sf.json.JSONArray;  

import net.sf.json.JSON ;  

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.Swap;  

import org.spring work.stereotype.Controller;  

import org.spring work.web.bind.annotation.RequestMapping;  
  
import com.anly.common.web.controller. Controller;  

  

/** 

 * @author anly 

 *  

 */  

@Controller  

@RequestMapping(value = \"/server\")  

public class ServerInfoController extends  Controller {  
     

    /** 

     * 服务器信息 

     */  

    @RequestMapping(value = \"\")  

    public void serverInfo(HttpServletResponse response) {  

        Properties props = System.getProperties();            

        Map<String, String> map = System.getenv();            

        JSON  json  = new JSON ();            

        json .put(\"server.user.name\", map.get(\"USERNAME\")); //用户名  

        json .put(\"server.computer.name\", map.get(\"COMPUTERNAME\")); //计算机名  

        json .put(\"server.computer.domain\", map.get(\"USERDOMAIN\")); //计算机域名            

        InetAddress addr = null;  

        try {  

            addr = InetAddress.getLocalHost();  

            json .put(\"server.ip\", addr.getHostAddress()); //本机ip  

            json .put(\"server.host.name\", addr.getHostName()); //本机主机名  
              
            json .put(\"server.user.home\", props.getProperty(\"user.home\")); //用户的主目录  

            json .put(\"server.user.dir\", props.getProperty(\"user.dir\")); //用户的当前工作目录  

        } catch (Exception e) {  

            logger.error(e.getMessage());  

        }            

        super.response2Client(response, json .toString());            

    }  

      

    /** 

     * 系统信息 

     */  

    @RequestMapping(value = \"/system\")  

    public void systemInfo(HttpServletResponse response) {  
          
        OperatingSystem OS = OperatingSystem.getInstance();  
          
        JSON  json  = new JSON ();            

        json .put(\"os.name\", OS.getVendorName()); //操作系统名称  

        json .put(\"os.arch\", OS.getArch()); //内核构架  

        json .put(\"os.de ion\", OS.getDe ion()); //操作系统的描述  

        json .put(\"os.version\", OS.getVersion()); //操作系统的版本号            

        super.response2Client(response, json .toString());            

    }  

      

    /** 

     * CPU信息 

     * @throws SigarException 

     */  

    @RequestMapping(value = \"/cpu\")  

    public void cpuInfo(HttpServletResponse response) throws SigarException {  
         
        Sigar sigar = new Sigar();           

        CpuInfo infos[] = sigar.getCpuInfoList();  

        CpuPerc cpuList[] = sigar.getCpuPercList();            

        JSON  json  = new JSON ();  
          
        JSONArray jsonArray = new JSONArray();  
          

        for (int i = 0, len = infos.length; i < len; i++) {// 不管是单块CPU还是多CPU都适用  
              
            CpuInfo info = infos[i];  
              
            JSON  jso = new JSON ();               

            jso.put(\"mhz\", info.getMhz()); //CPU的总量MHz  

            jso.put(\"company\", info.getVendor()); //CPU的厂商  

            jso.put(\"model\", info.getModel()); //CPU型号类别  

            jso.put(\"cache.size\", info.getCacheSize()); // 缓冲缓存数量  

            CpuPerc cpu = cpuList[i];  

            jso.put(\"freq.user\", CpuPerc.format(cpu.getUser())); //CPU的用户使用率  

            jso.put(\"freq.sys\", CpuPerc.format(cpu.getSys())); //CPU的系统使用率  

            jso.put(\"freq.wait\", CpuPerc.format(cpu.getWait())); //CPU的当前等待率  

            jso.put(\"freq.nice\", CpuPerc.format(cpu.getNice())); //CPU的当前错误率  

            jso.put(\"freq.idle\", CpuPerc.format(cpu.getIdle())); //CPU的当前空闲率  

            jso.put(\"freq.combined\", CpuPerc.format(cpu.getCombined())); //CPU总的使用率  

            jsonArray.add(jso);  

        }            

        json .put(\"cpu\", jsonArray);            

        super.response2Client(response, json .toString());            

    }  

      

    /** 

     * JVM信息 

     * @throws UnknownHostException 

     */  

    @RequestMapping(value = \"/jvm\")  

    public void jvmInfo(HttpServletResponse response) throws UnknownHostException {  
          
        Runtime r = Runtime.getRuntime();  

        Properties props = System.getProperties();           

        JSON  json  = new JSON ();           

        json .put(\"jvm.memory.total\", r.totalMemory()); //JVM可以使用的总内存  

        json .put(\"jvm.memory.free\", r.freeMemory()); //JVM可以使用的剩余内存  

        json .put(\"jvm.processor.avaliable\", r.availableProcessors()); //JVM可以使用的处理器个数  

        json .put(\"jvm.java.version\", props.getProperty(\"java.version\")); //Java的运行环境版本  

        json .put(\"jvm.java.vendor\", props.getProperty(\"java.vendor\")); //Java的运行环境供应商  

        json .put(\"jvm.java.home\", props.getProperty(\"java.home\")); //Java的安装路径  

        json .put(\"jvm.java.specification.version\", props.getProperty(\"java.specification.version\")); //Java运行时环境规范版本  

        json .put(\"jvm.java.class.path\", props.getProperty(\"java.class.path\")); //Java的类路径  

        json .put(\"jvm.java.library.path\", props.getProperty(\"java.library.path\")); //Java加载库时搜索的路径列表  

        json .put(\"jvm.java.io.tmpdir\", props.getProperty(\"java.io.tmpdir\")); //默认的临时文件路径  

        json .put(\"jvm.java.ext.dirs\", props.getProperty(\"java.ext.dirs\")); //扩展目录的路径  
          
        super.response2Client(response, json .toString());           

    }  

      

    /** 

     * 内存信息 

     * @throws SigarException 

     */  

    @RequestMapping(value = \"/memory\")  

    public void memoryInfo(HttpServletResponse response) throws SigarException {         

        Sigar sigar = new Sigar();  

        Mem mem = sigar.getMem();           

        JSON  json  = new JSON ();  
          
        json .put(\"memory.total\", mem.getTotal() / (1024 * 1024L));// 内存总量  

        json .put(\"memory.used\", mem.getUsed() / (1024 * 1024L));// 当前内存使用量  

        json .put(\"memory.free\", mem.getFree() / (1024 * 1024L));// 当前内存剩余量          

        Swap swap = sigar.getSwap();            

        json .put(\"memory.swap.total\", swap.getTotal() / (1024 * 1024L));// 交换区总量  

        json .put(\"memory.swap.used\", swap.getUsed() / (1024 * 1024L));// 当前交换区使用量  

        json .put(\"memory.swap.free\", swap.getFree() / (1024 * 1024L));// 当前交换区剩余量  
          
        super.response2Client(response, json .toString());  
          
    }  

      

    /** 

     * 磁盘文件信息 

     * @throws SigarException 

     */  

    @RequestMapping(value = \"/file\")  

    public void fileSystemInfo(HttpServletResponse response) throws SigarException {  
          
        Sigar sigar = new Sigar();          

        FileSystem fslist[] = sigar.getFileSystemList();            

        JSON  json  = new JSON ();            

        JSONArray jsonArray = new JSONArray();            

        for (int i = 0, len = fslist.length; i < len; i++) {                

            FileSystem fs = fslist[i];  
              
            JSON  jso = new JSON ();                

            jso.put(\"dev.name\", fs.getDevName()); //分区盘符名称  

            jso.put(\"dir.name\", fs.getDirName()); //分区盘符名称  

            jso.put(\"flags\", fs.getFlags()); //分区盘符类型  

            jso.put(\"sys.type.name\", fs.getSysTypeName()); //文件系统类型  

            jso.put(\"type.name\", fs.getTypeName()); //分区盘符类型名  

            jso.put(\"type\", fs.getType()); //分区盘符文件系统类型  

            FileSystemUsage usage = null;  
              

            try {  

                usage = sigar.getFileSystemUsage(fs.getDirName());  

            } catch (Exception e) {  

                logger.error(e.getMessage());  

            }  
              

            if(usage == null) {  

                continue;  

            }  

              
            switch (fs.getType()) {  

            case 0: // TYPE_UNKNOWN :未知  

                break;  

            case 1: // TYPE_NONE  

                break;  

            case 2: // TYPE_LOCAL_DISK : 本地硬盘  
                  

                jso.put(\"usage.totle\", usage.getTotal() / 1024); // 分区总大小  

                jso.put(\"usage.free\", usage.getFree() / 1024); // 分区剩余大小  

                jso.put(\"usage.avail\", usage.getAvail() / 1024); // 分区可用大小  

                jso.put(\"usage.used\", usage.getUsed() / 1024); // 分区已经使用量  

                jso.put(\"usage.use.percent\", usage.getUsePercent() * 100D); // 分区资源的利用率  

                break;  

            case 3:// TYPE_NETWORK :网络  

                break;  

            case 4:// TYPE_RAM_DISK :闪存  

                break;  

            case 5:// TYPE_CDROM :光驱  

                break;  

            case 6:// TYPE_SWAP :页面交换  

                break;  

            }  

            jso.put(\"disk.reads\", usage.getDiskReads()); // 读出  

            jso.put(\"disk.writes\", usage.getDiskWrites()); // 写入  
              
            jsonArray.add(jso);  

        }            

        json .put(\"file.system\", jsonArray);  
          
        super.response2Client(response, json .toString());            

    }  

      

    /** 

     * 网络信息 

     * @throws SigarException 

     */  

    @RequestMapping(value = \"/net\")  

    public void netInfo(HttpServletResponse response) throws SigarException {  
          
        Sigar sigar = new Sigar();  

        String ifNames[] = sigar.getNetInterfaceList();  
          
        JSON  json  = new JSON ();  
          
        JSONArray jsonArray = new JSONArray();           

        for (int i = 0, len = ifNames.length; i < len; i++) {                

            String name = ifNames[i];                

            JSON  jso = new JSON ();  
             
            NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);              
            jso.put(\"name\", name); // 网络设备名  

            jso.put(\"address\", ifconfig.getAddress()); // IP地址  

            jso.put(\"mask\", ifconfig.getNetmask()); // 子网掩码  
              

            if ((ifconfig.getFlags() & 1L) <= 0L) {  

                logger.info(\"!IFF_UP...skipping getNetInterfaceStat\");  

                continue;  

            }  
            
            NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);  

            jso.put(\"rx.packets\", ifstat.getRxPackets());// 接收的总包裹数  

            jso.put(\"tx.packets\", ifstat.getTxPackets());// 发送的总包裹数  

            jso.put(\"rx.bytes\", ifstat.getRxBytes());// 接收到的总字节数  

            jso.put(\"tx.bytes\", ifstat.getTxBytes());// 发送的总字节数  

            jso.put(\"rx.errors\", ifstat.getRxErrors());// 接收到的错误包数  

            jso.put(\"tx.errors\", ifstat.getTxErrors());// 发送数据包时的错误数  

            jso.put(\"rx.dropped\", ifstat.getRxDropped());// 接收时丢弃的包数  

            jso.put(\"tx.dropped\", ifstat.getTxDropped());// 发送时丢弃的包数  
              
            jsonArray.add(jso);  
              
        }            

        json .put(\"net\", jsonArray);  
          
        super.response2Client(response, json .toString());  
          
    }  

  

    /** 

     * 以太网信息 

     * @throws SigarException 

     */  

    @RequestMapping(value = \"/ethernet\")  

    public void ethernetInfo(HttpServletResponse response) throws SigarException {  

        Sigar sigar = new Sigar();  

        String[] ifaces = sigar.getNetInterfaceList();  
          
        JSON  json  = new JSON ();  
     
        JSONArray jsonArray = new JSONArray();           

        for (int i = 0, len = ifaces.length; i < len; 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;  

            }               

            JSON  jso = new JSON ();                

            jso.put(\"address\", cfg.getAddress());// IP地址  

            jso.put(\"broad.cast\", cfg.getBroadcast());// 网关广播地址  

            jso.put(\"hwaddr\", cfg.getHwaddr());// 网卡MAC地址  

            jso.put(\"net.mask\", cfg.getNetmask());// 子网掩码  

            jso.put(\"de ion\", cfg.getDe ion());// 网卡描述信息  

            jso.put(\"type\", cfg.getType());// 网卡类型               

            jsonArray.add(jso);  
             
        }  

        json .put(\"ethernet\", jsonArray);            

        super.response2Client(response, json .toString());            

    }        

}  

 

收藏 打印