用com4j调用wmi关闭windows和获取系统日志

接上回,接下来是关机,这个需要用到权限哦

PS:以下代码都在windows xp上运行通过,windows 7会有什么表现我还不确定,虽然我现在用的是win7,懒得测试了。但有一点可以确定,wsh的regWrite和regDelete在win7上是不会成功的,我估计是win7的安全机制在其作用。

至于vista,啊,vista是什么?

 

    private void shutdownInWindows() {//接上回
        ISWbemLocator wbemLocator = ClassFactory.createSWbemLocator();
        ISWbemServices wbemServices = wbemLocator.connectServer("localhost",
                "Root\\CIMv2", "", "", "", "", 0, null);
        ISWbemSecurity security = wbemServices.security_();//调用安全接口
        security.privileges().add(WbemPrivilegeEnum.wbemPrivilegeShutdown, true);//打开关机权限,必须,否则windows不予理睬...
        security.impersonationLevel(WbemImpersonationLevelEnum.wbemImpersonationLevelImpersonate);
        ISWbemObjectSet result = wbemServices.execQuery(
                "Select * From Win32_OperatingSystem", "WQL", 16, null);//使用wql获得操作系统对象
        for (Com4jObject obj : result) {
            ISWbemObject wo = obj.queryInterface(ISWbemObject.class);
            wo.execMethod_("Shutdown", null, 0, null);//调用关机命令,OK
        }
    }

 然后呢,是获取系统日志,很强大啊

 

   private void getEventsInWindowsWithCondition(Set<Event> set, int logType, String condition) {
        ISWbemLocator wbemLocator = ClassFactory.createSWbemLocator();
        ISWbemServices wbemServices = wbemLocator.connectServer("localhost",
                "Root\\CIMv2", "", "", "", "", 0, null);
        ISWbemObjectSet result = wbemServices.execQuery(//wql,MSDN上可以查到的,不用多少了
                "Select EventType,TimeGenerated,SourceName,Message,EventCode From Win32_NTLogEvent Where Logfile = '" + Event.LogType.valueOf(logType) + "'" + condition, "WQL", 16, null);
        for (Com4jObject obj : result) {
            ISWbemObject wo = obj.queryInterface(ISWbemObject.class);
            Event e = new Event();
            e.setLogType(logType);
            e.setEventType((Short) wo.properties_("EventType", 0).value());//获取字段值
            e.setDate(parseDate(wo.properties_("TimeGenerated", 0).value()));
            e.setSource((String) wo.properties_("SourceName", 0).value());
            e.setMessage((String) wo.properties_("Message", 0).value());
            e.setCode((Integer) wo.properties_("EventCode", 0).value());
            set.add(e);
        }
    }