Java用wmi4j遠程管理Windows服務

原文請訪問:http://www.chenlichao.cn/opensource/74.html
html

wmi4j是純Java實現的Windows WMI客戶端,它基於j-interop針對WMI從新封裝,提供了更便捷的方法,能知足基本的windows管理,包括服務管理,性能查詢,執行腳本等等。java

wmi4j下載

用Maven的朋友們能夠直接引入,groupId=cn.chenlichao, artifactId=wmi4j, version=0.9。 源碼地址: Github: https://github.com/chenlichao-cn/wmi4j使用其餘構件框架的朋友,能夠去maven中央庫或者http://maven.oschina.net查詢wmi4j,固然要記得下載它的依賴包:git

  • org.glassfish.main.external:j-interop-repackaged:4.0github

  • org.slf4j:slf4j-api:1.7.7apache

  • org.apache.commons:commons-lang3:3.1windows

使用wmi4j管理Windows服務

用wmi4j管理很方便,少許代碼就能夠完成功能,下面咱們用一個實際的例子來演示如何獲取服務列表,查詢服務,獲取指定服務狀態,啓動服務和中止服務幾個最經常使用的功能。api

WMI相關的文檔,請參考微軟官方文檔: WMI Reference服務器

public static void main(String[] args) {
   //設定鏈接參數
   String server = "192.168.1.201";
   String username = "administrator";
   String password = "password";
   String namespace = "root\\cimv2";
 
   //構建鏈接器
   SWbemLocator locator = new SWbemLocator(server,username,password,namespace);
 
   try {
   //鏈接遠程服務器
   SWbemServices wbemServices = locator.connectServer();
 
   //遍歷服務列表
   SWbemObjectSet services = wbemServices.instancesOf("Win32_Service");
   System.out.println("服務數量: " + services.getCount());
   Iterator<SWbemObject> iterator = services.iterator();
   while(iterator.hasNext()) {
       SWbemObject service = iterator.next();
       System.out.println(service.getObjectText());
       System.out.println("-----------------------------------------------");
       break; //服務不少,就只打一個吧
   }
 
   //查詢Windows開頭的服務
   SWbemObjectSet winServices = wbemServices.execQuery(
            "select * from Win32_Service where DisplayName like 'Windows%'");
   System.out.println("Windows開頭的服務數: " + winServices.getCount());
 
   //經過服務名,直接獲取服務。
   //注意: 服務名不是services.msc列表裏顯示的名稱,顯示的名稱是DisplayName屬性,
   //而get方法必須使用主鍵屬性Name. 例如: Application Management服務,
   //在services.msc是這樣顯示的, 但它服務名是AppMgmt, 能夠經過屬性查看。
   SWbemObject dhcpClient = wbemServices.get("Win32_Service.Name='AppMgmt'");
   System.out.println("服務名: " + dhcpClient.getPropertyByName("Name")
               .getStringValue());
   System.out.println("顯示名: " + dhcpClient.getPropertyByName("DisplayName")
               .getStringValue());
   //獲取服務狀態
   System.out.println("狀態: " + dhcpClient.getPropertyByName("State").getStringValue());
 
   //啓動服務
  dhcpClient.execMethod("StartService");
  System.out.println("啓動後的狀態: " + wbemServices.get("Win32_Service.Name='AppMgmt'")
    .getPropertyByName("State").getStringValue());
 
  //中止服務
  dhcpClient.execMethod("StopService");
  System.out.println("再次中止後的狀態: " 
          + wbemServices.get("Win32_Service.Name='AppMgmt'")
                .getPropertyByName("State").getStringValue());
 
   } catch (WMIException e) {
       e.printStackTrace();
   } catch (UnknownHostException e) {
       e.printStackTrace();
   }
}
相關文章
相關標籤/搜索