1. 程式人生 > >WMI實現遠端監控多臺windows伺服器

WMI實現遠端監控多臺windows伺服器

簡介

WMI簡介:

WMI(Windows Management Instrumentation,Windows 管理規範)是一項核心的 Windows 管理技術;使用者可以使用 WMI 管理本地和遠端計算機。

WQL簡介:

WQL就是WMI中的查詢語言,WQL的全稱是WMI Query Language,簡稱為WQL,翻譯成中文好像可以成為Windows管理規範查詢語言。熟悉SQL語言的朋友會感覺它和SQL非常相似。

WQL其實非常簡單,它有如下特點:

1、每個WQL語句必須以SELECT開始;

2、SELECT後跟你需要查詢的屬性名(我剛才對應SQL將其稱之為欄位名了),也可以像SQL一樣,以*表示返回所有屬性值;

3、FROM關鍵字;

4、你要查詢的類的名字;

5、另外,如果你想精確查詢結果還可以加上WHERE條件從句。比如某個類有Enable屬性,你可以在查詢的時候加上WHERE ENABLE=true,條件可以新增and or等關係操作。

如以下的都是正確的WQL語句:

Select * From Win32_LogicalDisk where drivetype=3    ’‘’‘查詢所有硬碟分割槽

SELECT * FROM Win32_share  ’‘查詢所有共享目錄

SELECT * FROM Win32_NetworkAdapterConfiguration WHERE DHCPEnabled=TRUE

SELECT Description FROM Win32_Account WHERE Name='Administrator'

SELECT Freespace,DeviceID FROM Win32_LogicalDisk

在搜尋框輸入wbemtest即可檢視WQL測試工具

轉載:http://my.oschina.net/noahxiao/blog/73163

1、環境準備

a、windows要開啟Remote Registry與Windows Management Instrumentation服務

b、禁用放火牆

c、window2008系統登錄檔越獄(高版本的win)

需要修改regedit中HKEY_CLASSES_ROOT\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}的許可權,windows2008不再給Administrators完全控制權。

http://files.helgeklein.com/downloads/SetACL/current/SetACL%20(executable%20version).zip

set_wmi_reg_acl.cmd

SetACL.exe -on "HKEY_CLASSES_ROOT\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}" -ot reg -actn setowner -ownr "n:Administrators"

SetACL.exe -on "HKEY_CLASSES_ROOT\CLSID\{76A64158-CB41-11D1-8B02-00600806D9B6}" -ot reg -actn ace -ace "n:Administrators;p:full"

以超級管理員身份執行這個cmd,就會把owner與完全控制權限授予Administrators組

注意這裡需要把這個cmd命令和SetACL.exe copy到C:\Windows\System32資料夾

2、程式程式碼

java類

import org.jinterop.dcom.common.JIException;

import org.jinterop.dcom.common.JISystem;

import org.jinterop.dcom.core.*;

import org.jinterop.dcom.impls.JIObjectFactory;

import org.jinterop.dcom.impls.automation.IJIDispatch;

import org.jinterop.dcom.impls.automation.IJIEnumVariant;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import java.net.UnknownHostException;

import java.util.logging.Level;

 

/**

 * Created with IntelliJ IDEA.

 * User: noah

 * Date: 8/16/12

 * Time: 8:00 AM

 * To change this template use File | Settings | File Templates.

 */

public class WmiService {

 

    private JIComServer m_ComStub = null;

    private IJIComObject m_ComObject = null;

    private IJIDispatch m_Dispatch = null;

    private String m_Address = null;

    private JISession m_Session = null;

    private IJIDispatch m_WbemServices = null;

 

    private static final String WMI_CLSID = "76A6415B-CB41-11d1-8B02-00600806D9B6";

    private static final String WMI_PROGID = "WbemScripting.SWbemLocator";

 

    private Logger logger = LoggerFactory.getLogger(this.getClass());

 

 

    public WmiService(String address) {

        JISystem.setAutoRegisteration(true);

        JISystem.getLogger().setLevel(Level.WARNING);

        m_Address = address;

    }

 

    public void query(String strQuery) {

 

        System.out.println("query:" + strQuery);

 

        JIVariant results[] = new JIVariant[0];

        try {

            results = m_WbemServices.callMethodA("ExecQuery", new Object[]{new JIString(strQuery), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM()});

            IJIDispatch wOSd = (IJIDispatch) JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());

 

            int count = wOSd.get("Count").getObjectAsInt();

 

            IJIComObject enumComObject = wOSd.get("_NewEnum").getObjectAsComObject();

            IJIEnumVariant enumVariant = (IJIEnumVariant) JIObjectFactory.narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));

 

            IJIDispatch wbemObject_dispatch = null;

 

            for (int c = 0; c < count; c++) {

 

                Object[] values = enumVariant.next(1);

                JIArray array = (JIArray) values[0];

                Object[] arrayObj = (Object[]) array.getArrayInstance();

                for (int j = 0; j < arrayObj.length; j++) {

                    wbemObject_dispatch = (IJIDispatch) JIObjectFactory.narrowObject(((JIVariant) arrayObj[j]).getObjectAsComObject());

                }

 

                String str = (wbemObject_dispatch.callMethodA("GetObjectText_", new Object[]{1}))[0].getObjectAsString2();

                System.out.println("(" + c + "):");

                System.out.println(str);

                System.out.println();

            }

 

 

        } catch (JIException e) {

            e.printStackTrace();

        }

    }

 

    public void connect(final String domain, final String username, final String password) {

        try {

 

            m_Session = JISession.createSession(domain, username, password);

            m_Session.useSessionSecurity(true);

            m_Session.setGlobalSocketTimeout(5000);

 

            m_ComStub = new JIComServer(JIProgId.valueOf(WMI_PROGID), m_Address, m_Session);

 

            IJIComObject unknown = m_ComStub.createInstance();

            m_ComObject = unknown.queryInterface(WMI_CLSID);

 

            m_Dispatch = (IJIDispatch) JIObjectFactory.narrowObject(m_ComObject.queryInterface(IJIDispatch.IID));

            JIVariant results[] = m_Dispatch.callMethodA(

                    "ConnectServer",

                    new Object[]{

                            new JIString(m_Address),

                            JIVariant.OPTIONAL_PARAM(),

                            JIVariant.OPTIONAL_PARAM(),

                            JIVariant.OPTIONAL_PARAM(),

                            JIVariant.OPTIONAL_PARAM(),

                            JIVariant.OPTIONAL_PARAM(),

                            0,

                            JIVariant.OPTIONAL_PARAM()

                    }

            );

 

            m_WbemServices = (IJIDispatch) JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());

 

        } catch (JIException e) {

            e.printStackTrace();

            if (m_Session != null) {

                try {

                    JISession.destroySession(m_Session);

                } catch (JIException e1) {

                    logger.error(e.getMessage(), e);

                }

            }

        } catch (UnknownHostException e) {

            if (m_Session != null) {

                try {

                    JISession.destroySession(m_Session);

                } catch (JIException e1) {

                    logger.error(e.getMessage(), e);

                }

            }

        }

    }

 

    public void disconnect() {

        try {

            JISession.destroySession(m_Session);

        } catch (JIException e) {

            logger.error(e.getMessage(), e);

        }

    }

 

 

    public static void main(String[] args) {

 

        WmiService wmiService = new WmiService("172.16.158.129");

 

        //域(一般為空字元),使用者名稱,密碼

        注意:連結的使用者一定是超級管理員Administrator

        wmiService.connect("", "username", "password");

 

        //系統資訊

        wmiService.query("SELECT * FROM Win32_ComputerSystem");

 

        //CPU資訊

        wmiService.query("SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name != '_Total'");

 

        //記憶體資訊

        wmiService.query("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");

 

        //磁碟資訊

        wmiService.query("SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk Where Name != '_Total'");

 

        wmiService.disconnect();

    }

}

mavne配置(pom.xml)

        <dependency>

            <groupId>org.kohsuke.jinterop</groupId>

            <artifactId>j-interop</artifactId>

            <version>2.0.8-kohsuke-1</version>

        </dependency>