Chinaunix首页 | 论坛 | 博客
  • 博客访问: 809580
  • 博文数量: 167
  • 博客积分: 7173
  • 博客等级: 少将
  • 技术积分: 1671
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-04 23:07
文章分类

全部博文(167)

文章存档

2018年(1)

2017年(11)

2012年(2)

2011年(27)

2010年(88)

2009年(38)

分类: Java

2010-11-03 17:23:06




有时候需要采集服务器的一些信息,例如:win linux solaris等,如果使用平台相关的代码,
那么需要维护很多套程序。找网上找找发现有个第三方的工具还挺好用,sigar,它支持的语言
有perl python c++ Java,然后我这边拿Java来做一个常识(Java的System也能获取一些
基本的系统信息,但不详细),(python 可以使用ctypes platform进行获取也可以使用这个sigar);

Sigar(System Information Gatherer And Reporter)
/sigar,是一个开源的工具,提供了跨平台的系统信息收集的API,由C语言实现的。可以收集的信息包括:


1, CPU信息,包括基本信息(vendor、model、mhz、cacheSize)和统计信息(user、sys、idle、nice、wait)
2, 文件系统信息,包括Filesystem、Size、Used、Avail、Use%、Type
3, 事件信息,类似Service Control Manager
4, 内存信息,物理内存和交换内存的总数、使用数、剩余数;RAM的大小
5, 网络信息,包括网络接口信息和网络路由信息
6, 进程信息,包括每个进程的内存、CPU占用数、状态、参数、句柄
7, IO信息,包括IO的状态,读写大小等
8, 服务状态信息
9, 系统信息,包括操作系统版本,系统资源限制情况,系统运行时间以及负载,JAVA的版本信息等.
(后面以java代码做个实例)

但是,还是不能在win上获取磁盘驱动器信息,所以借助了一下wmi:
参考的文章:



wmi 数据库对照表

我所需要的具体对照

   
WMI最 初是内置在Windows 2000、Windows XP和Window 2003系列操作系统中核心的管理支持技术,目前WMI已
经是一种规范和基础 结构,通过它可以访问、配置、管理和监视几乎所有的Windows资源例如磁盘、事件日
志、文件、文件夹、文件系统、网络组件、操作系统设置、性能数据、 打印机、进程、注册表设置、安全性、
服务、共享、用户、组等等。在WMI之前,能够以编程方式访问Windows资源的惟一方法就是通过 Win32 API,
现在我们除了使用WMI脚本管理任何通过WMI公开的Windows资源外,还可以通过.Net框架对于WMI封装的 System.Management
命名空间来轻松实现。

我们首先使用WMI查询来获取特定类名的SelectQuery实例,可以有两种方法创建该实例,一是可以传递一个已
知的类名,譬如本文需要传递的类名为:
Win32_LogicalDisk,代码如下:

SelectQuery selectQuery = new SelectQuery("win32_logicaldisk");
或者使用wql查询来创建查询类的实例,代码如下:

SelectQuery selectQuery = new SelectQuery("select * from win32_logicaldisk");
或者只获取类的部分属性,代码如下:
SelectQuery selectQuery = new SelectQuery("select Name,DriveType from win32_logicaldisk");

WQL查询语言是SQL
的 一个子集,查询通过包含以下内容限制返回的数据量1、SELECT子句,指定只返回某些属性的数据;2、
WHERE子句,指定要返回的实例。 Win32_LogicalDisk类在默认的本地MSDN里是无法找到的,只有在联机的MSDN
 里,Win32 and COM Development下的WMI下才能找到,同样可以使用的类还有很多很多,包含登录用户信息的
 Win32_Account类、包含本地和共享打印机信息的Win32_PrinterShare类等等。Win32_LogicalDisk里所包含的
 驱动器属性相当丰富,如下图:


为了速度用vbscript写了个测试一下:
strComputer = "."
Set objWMIService = GetObject( _
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery( _
    "Select * from Win32_DiskDrive")
For Each objItem in colItems
    Wscript.Echo "Device ID: " & objItem.DeviceID
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo "Name: " & objItem.Name 
    Wscript.Echo "PNPDeviceID: " & objItem.PNPDeviceID 
Next






JAVA:


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 sun.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.net.InetAddress;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.OperatingSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;


public class baseinfo {

    /**
     * Edit by Sky 20101029
     */
    private String memsize="";//记录物理内存的大小
    private int kb = 1024*1024;//计算单位
    private String osinfo="";//记录系统版本等类别信息
   


   
    private String mem(){
        OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
        memsize="mem_="+totalMemorySize+"M";
        return memsize;
    }
   
    private String cpu(){
          Sigar sigar = new Sigar();
          String cpuinfo="";
          CpuInfo[] infos;
          try {
               infos = sigar.getCpuInfoList();
               cpuinfo+=infos[0].getModel();
               int cpunum=infos.length/2;
               if(cpunum>0){
                  cpuinfo+=" ,"+cpunum+"CPU";
               }else{
                   cpuinfo+=" ,1CPU";
               }
          } catch (SigarException e) {
           e.printStackTrace();
          }
               cpuinfo+=","+Runtime.getRuntime().availableProcessors()+"CORE";
        return "cpu_="+cpuinfo;
    }
   
    private String disk(){
        String osName = System.getProperty("os.name");
        //System.out.println(osName);
        String diskinfo="";
        long total=0;
        try{
           
          Sigar disk = new Sigar();
          FileSystem fslist[]=disk.getFileSystemList();
          if(osName.startsWith("Win") || osName.startsWith("win")){
            for (int i = 0; i < fslist.length; i++) {  
                FileSystem fs = fslist[i];    // 分区的盘符名称  
                 if (fs.getType() == 2) {
                //System.out.println("\n~~~~~~~~~~" + i + "~~~~~~~~~~");   
                //System.out.println("fs.getDevName() = " + fs.getDevName());
                FileSystemUsage usage = disk.getFileSystemUsage(fs.getDirName());
                total=total+usage.getTotal()/kb;
                //System.out.println(" Total = " + usage.getTotal()/kb + "G");
               }
             }
            diskinfo+="disk_="+total+"G";
          }else if(osName.startsWith("Lin") || osName.startsWith("lin")){
                long count=0;
                HashMap hm=new HashMap();
              
              for (int i = 0; i < fslist.length; i++) {  
                    FileSystem fs = fslist[i];    // 分区的盘符名称    
                     if (fs.getType() == 2) {
                         count=0;
                         String devName = fs.getDevName();
                         String subdevName = devName.substring(0, devName.length()-1);
                         if(hm.containsKey(subdevName)){
                             int myvalue=Integer.parseInt(hm.get("subdevName").toString());
                             FileSystemUsage usage = disk.getFileSystemUsage(fs.getDirName());
                             count=count+usage.getTotal()/kb;
                             count=count+myvalue;
                             hm.remove(subdevName);
                             diskinfoclass di=new diskinfoclass(subdevName,count);
                             hm.put(subdevName, di);
                         }else{
                             FileSystemUsage usage = disk.getFileSystemUsage(fs.getDirName());
                             count=count+usage.getTotal()/kb;
                             diskinfoclass di=new diskinfoclass(subdevName,count);
                             hm.put(subdevName, di);
                         }
                   }
                     Collection collection = hm.values();
                     Iterator iter = collection.iterator();
                     diskinfo+="disk_";
                     String tmpstring="";
                     while(iter.hasNext()){
                         diskinfoclass te=iter.next();
                         tmpstring+=te.getName()+":"+te.getSize()+" ";
                     }
                     diskinfo+=tmpstring;
                     System.out.println("diskinfo:"+diskinfo);
                 }
          }
         
        } catch(SigarException e) {  
            e.printStackTrace();  
            }
       
        return diskinfo;
    }
   
    private String controller(){
        String controllerinfo="";
        String scsictlinfo="";
          Sigar sigar = null;  
          String ethernet_controller="";
          try {   
              sigar = new Sigar();
              String[] ifaces = sigar.getNetInterfaceList();
              for (int i = 0; i < ifaces.length; i++) {
                  NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
                  String str=new String(cfg.getDescription().getBytes(),"UTF-8");
                  str=str.replace("?", "");
                  ethernet_controller+=cfg.getType()+" controller:"+str;

              }
          }catch(Exception e){
              e.printStackTrace();
          }
        //////////////scsictlinfo///////////////////////
         
            try {
                String[] vbsCmd   = new String[]{"wscript", "my.vbs"}; 
                Process process = Runtime.getRuntime().exec(vbsCmd);
                List processes = new LinkedList();
                processes.add(process); 
                 for (Process p : processes)  
                 {  
                        try {
                            p.waitFor();
                        } catch (InterruptedException e) {
                           
                            e.printStackTrace();
                        }  
                 }  
                File filedisk = new File("disktype.txt");
                if(filedisk.exists()){
                InputStream is = new FileInputStream("disktype.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line = reader.readLine();
                while (line != null) {
                    line=line.substring(line.indexOf("\\")+1,line.indexOf("______________________________"));
                    scsictlinfo+=line;
                    line = reader.readLine();
                }
                is.close();
                reader.close();}else{
                    scsictlinfo+="unkown disk drive type";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        ////////////////////////////////////////////////
        return controllerinfo+="scsictl_="+scsictlinfo+"\nethctl_="+ethernet_controller;
    }
   
    private String nic(){
        String nicinfo="";
          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(cfg.getName().indexOf("lo0")<0){
                  nicinfo+= cfg.getName()+"("+cfg.getHwaddr()+"|"+cfg.getAddress()+")";
                }
              }
          }catch(Exception e){
              e.printStackTrace();
          }
        return nicinfo;
    }
   
    private String osinfo(){
        String osName = System.getProperty("os.name");
        String kernel = osName +" "+ System.getProperty("os.version");
        String issue = "";
        String hostname="";
        String bit="";
        String uptime="";
          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();
           }
          }
       OperatingSystem OS = OperatingSystem.getInstance();
       issue=OS.getDescription()+"  ("+OS.getVendorCodeName()+")";
       bit=OS.getArch();
       if(osName.startsWith("Win") || osName.startsWith("win") ){
         try{
             Process readresult = Runtime.getRuntime().exec("uptime.exe");
             BufferedReader in = new BufferedReader(new InputStreamReader(readresult.getInputStream()));
             String line="";
             line = in.readLine();
             if(line.indexOf("day")>0)
               uptime=(line.substring(line.indexOf("for:")+4,line.indexOf("day")));
             else
               uptime=(line.substring(line.indexOf("for:")+4,line.indexOf(",")));
             in.close();
             in=null;
         }catch(Exception e){
           e.printStackTrace();
              }
         }else{
             try{
             Process readresult = Runtime.getRuntime().exec("/usr/bin/uptime");
             BufferedReader in = new BufferedReader(new InputStreamReader(readresult.getInputStream()));
             String line="";
             line = in.readLine();
             uptime=(line.substring(line.indexOf("up")+2,line.indexOf("day")));
             in.close();
             in=null;
             }catch(Exception e){
                 e.printStackTrace();
             }
         }
       if(bit.startsWith("x86")|| bit.startsWith("X86")){
           bit="64bit";
       }else{ bit = "32bit";}
      
        osinfo = "os_="+osName+"\nkernel_="+kernel+"\nissue_="+issue+"\nbit_="+bit+"\nhostname_="+hostname+"\nrundays_="+uptime;
        return osinfo;
       
    }
   
    public String getInfo(){
        String output="";
        agent myagent= new agent();
        output+=this.cpu()+"\n"+this.mem()+"\n"+this.disk()+"\n"+this.controller()+"\n"+this.nic()+"\n"+this.osinfo()+"\n"+myagent.getVersion();
        return output;
    }
     
    public static void main(String[] args) {
        //System.out.println(System.getProperty("java.library.path"));
        baseinfo test = new baseinfo();
        //System.out.println(test.mem());
        //System.out.println(test.osinfo());
        //test.getCpuTotal();
        //System.out.println(test.disk());
        //System.out.println(test.cpu());
        //System.out.println(test.nic());
        //System.out.println(test.controller());
        System.out.println(test.getInfo());

    }

}




在linux、solaris上也是可行,不过要改一下一些计算方式。




阅读(2555) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-11-05 01:01:55

sky大大,偶像啊。收我为徒吧!%>_<%