1
import wmi
import win32com.client
def Usb_detect():

 raw_wql = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_USBHub\'"
 c = wmi.WMI ()
 watcher = c.watch_for(raw_wql=raw_wql)
 # while 1:
 usb = watcher()
 #<class 'wmi._wmi_event'>
 return usb  

print(Usb_detect())

OUTPUT:

   instance of Win32_USBHub
{
        Caption = "USB Composite Device ";
        ConfigManagerErrorCode = 0;
        ConfigManagerUserConfig = FALSE;
        CreationClassName = "Win32_USBHub";
        Description = "USB Composite Device ";
        DeviceID = "xyz";
        Name = "USB Composite Device ";
        PNPDeviceID = "xyz";
        Status = "OK";
        SystemCreationClassName = "Win32_ComputerSystem";
        SystemName = "xyz";
};

I want to convert this WMI object to json using python. Please suggest me a solution. I have tried different ways but not able to get a reference.

1 Answers1

0

I was recently working on a case which I had to handle _wmi_event as _wmi_object for a process monitoring app. here is the code sample I wrote for this scenario, you can convert the dict object to json easily:

import wmi


def wmiToDict(wmi_object):
    return dict((attr, getattr(wmi_object, attr)) for attr in wmi_object.__dict__['_properties'])


class WindowsProcessWatcher:
    def __init__(self, computer=None):
        self.c = wmi.WMI(computer)

    def watchCreate(self):
        process_watcher = self.c.Win32_Process.watch_for(
            notification_type="Creation")
        
        p = wmi._wmi_object(process_watcher())
        return wmiToDict(p)

local_wpw = WindowsProcessWatcher()
local_wpw.watchCreate()
N.S
  • 1,363
  • 15
  • 18