Python wmi.WMI Examples

The following are 30 code examples of wmi.WMI(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wmi , or try the search function .
Example #1
Source File: gen.py    From multibootusb with GNU General Public License v2.0 7 votes vote down vote up
def process_exist(process_name):
    """
    Detect if process exist/ running and kill it.
    :param process_name: process name to check
    :return: True if processis killed else False
    """
    if platform.system() == 'Windows':
        import signal
        import wmi
        c = wmi.WMI()
        for process in c.Win32_Process():
            if process_name in process.Name:
                log(process_name + ' exist...')
                log(str(process.ProcessId) + ' ' + str(process.Name))
                log("Having Windows explorer won't allow dd.exe to write ISO image properly."
                      "\nKilling the process..")
                try:
                    os.kill(process.ProcessId, signal.SIGTERM)
                    return True
                except:
                    log('Unable to kill process ' + str(process.ProcessId))

    return False 
Example #2
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def associators(self, wmi_association_class="", wmi_result_class=""):
        """Return a list of objects related to this one, optionally limited
        either by association class (ie the name of the class which relates
        them) or by result class (ie the name of the class which would be
        retrieved)::

          c = wmi.WMI ()
          pp = c.Win32_ParallelPort ()[0]

          for i in pp.associators (wmi_association_class="Win32_PortResource"):
            print i

          for i in pp.associators (wmi_result_class="Win32_PnPEntity"):
            print i
        """
        try:
            return [
                _wmi_object(i) for i in \
                self.ole_object.Associators_(
                    strAssocClass=wmi_association_class,
                    strResultClass=wmi_result_class
                )
            ]
        except pywintypes.com_error:
            handle_com_error() 
Example #3
Source File: openhwmon.py    From grid-control with GNU General Public License v3.0 6 votes vote down vote up
def initialize_hwmon():
    """Create a WMI object and verify that OpenHardwareMonitor is installed."""

    # Access the OpenHWMon WMI interface
    try:
        hwmon = wmi.WMI(namespace="root\OpenHardwareMonitor")
        return hwmon

    # WMI exception (e.g. no namespace "root\OpenHardwareMonitor" indicates OpenHWMon is not installed
    except:
        helper.show_error("OpenHardwareMonitor WMI data not found.\n\n"
                          "Please make sure that OpenHardwareMonitor is installed.\n\n"
                          "Latest version is available at:\n\n"
                          "http://openhardwaremonitor.org\n\n"
                          "The application will now exit.")
        sys.exit(0) 
Example #4
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def Registry(
        computer=None,
        impersonation_level="Impersonate",
        authentication_level="Default",
        authority=None,
        privileges=None,
        moniker=None
):
    warnings.warn("This function can be implemented using wmi.WMI (namespace='DEFAULT').StdRegProv", DeprecationWarning)
    if not moniker:
        moniker = construct_moniker(
            computer=computer,
            impersonation_level=impersonation_level,
            authentication_level=authentication_level,
            authority=authority,
            privileges=privileges,
            namespace="default",
            suffix="StdRegProv"
        )
    
    try:
        return _wmi_object(GetObject(moniker))
    
    except pywintypes.com_error:
        handle_com_error() 
Example #5
Source File: WMIStorageProvider.py    From AltFS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, machine_identification_string, **kwargs):
        """Constructor for UserDefaultsStorageProvider"""
        super(WMIStorageProvider, self).__init__()
        self._machine_id_string = machine_identification_string
        self._wmi_client = wmi.WMI()
        self._wmi_client_dll = ctypes.cdll.LoadLibrary(
            os.path.join(os.path.dirname(__file__), WMI_CLIENT_DLL_PATH))
        self._namespace = kwargs["namespace"]
        self._class_name = self._generate_bucket_name()
        # calculate number of available buckets, used for modulus division
        # when calculating the bucket index
        self._buckets_names = [self._class_name]
        self._buckets_count = len(self._buckets_names)
        self._create_bucket()
        logger.debug("namespace: %s" % self._namespace)
        logger.debug("root class name: %s" % self._class_name) 
Example #6
Source File: baseutils.py    From os-win with Apache License 2.0 6 votes vote down vote up
def _compat_conn(self):
        if not self._compat_conn_attr:
            if not BaseUtilsVirt._os_version:
                # hostutils cannot be used for this, it would end up in
                # a circular import.
                os_version = wmi.WMI().Win32_OperatingSystem()[0].Version
                BaseUtilsVirt._os_version = list(
                    map(int, os_version.split('.')))

            if BaseUtilsVirt._os_version >= [6, 3]:
                self._compat_conn_attr = self._conn
            else:
                self._compat_conn_attr = self._get_wmi_compat_conn(
                    moniker=self._wmi_namespace % self._host)

        return self._compat_conn_attr 
Example #7
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def _get_keys(self):
        """A WMI object is uniquely defined by a set of properties
        which constitute its keys. Lazily retrieves the keys for this
        instance or class.

        :returns: list of key property names
        """
        # NB You can get the keys of an instance more directly, via
        # Path\_.Keys but this doesn't apply to classes. The technique
        # here appears to work for both.
        if self._keys is None:
            _set(self, "_keys", [])
            for property in self.ole_object.Properties_:
                for qualifier in property.Qualifiers_:
                    if qualifier.Name == "key" and qualifier.Value:
                        self._keys.append(property.Name)
        return self._keys 
Example #8
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def watch_for(
            self,
            notification_type="operation",
            delay_secs=1,
            fields=[],
            **where_clause
    ):
        if self._namespace is None:
            raise x_wmi_no_namespace("You cannot watch directly from a WMI class")
        
        valid_notification_types = ("operation", "creation", "deletion", "modification")
        if notification_type.lower() not in valid_notification_types:
            raise x_wmi("notification_type must be one of %s" % ", ".join(valid_notification_types))
        
        return self._namespace.watch_for(
            notification_type=notification_type,
            wmi_class=self,
            delay_secs=delay_secs,
            fields=fields,
            **where_clause
        ) 
Example #9
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def query(self, fields=[], **where_clause):
        """Make it slightly easier to query against the class,
         by calling the namespace's query with the class preset.
         Won't work if the class has been instantiated directly.
        """
        #
        # FIXME: Not clear if this can ever happen
        #
        if self._namespace is None:
            raise x_wmi_no_namespace("You cannot query directly from a WMI class")
        
        try:
            field_list = ", ".join(fields) or "*"
            wql = "SELECT " + field_list + " FROM " + self._class_name
            if where_clause:
                wql += " WHERE " + " AND ".join(["%s = %r" % (k, str(v)) for k, v in where_clause.items()])
            return self._namespace.query(wql, self, fields)
        except pywintypes.com_error:
            handle_com_error() 
Example #10
Source File: vss.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def select_shadow_copy(self):
        wmi_instance = wmi.WMI()
        list_shadowCopy = wmi_instance.Win32_ShadowCopy()
        for sh in list_shadowCopy:
            if sh.ID == self.uid:
                return sh 
Example #11
Source File: vss.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def list_shadow_copy():
        wmi_instance = wmi.WMI()
        list_shadowCopy = wmi_instance.Win32_ShadowCopy()
        for sh in list_shadowCopy:
            print sh 
Example #12
Source File: client.py    From canisrufus with GNU General Public License v3.0 5 votes vote down vote up
def _detectDevices(self):
        pythoncom.CoInitialize()
        devs = []
        w = wmi.WMI ()
        for dev in w.Win32_PnPEntity ():
            devs.append('{0};{1}'.format(dev.Name, dev.Manufacturer))
        return devs 
Example #13
Source File: baseutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def _get_wmi_obj(self, moniker, **kwargs):
        return wmi.WMI(moniker=moniker, **kwargs) 
Example #14
Source File: baseutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def _vs_man_svc(self):
        if self._vs_man_svc_attr:
            return self._vs_man_svc_attr

        vs_man_svc = self._compat_conn.Msvm_VirtualSystemManagementService()[0]
        if BaseUtilsVirt._os_version >= [6, 3]:
            # NOTE(claudiub): caching this property on Windows / Hyper-V Server
            # 2012 (using the old WMI) can lead to memory leaks. PyMI doesn't
            # have those issues, so we can safely cache it.
            self._vs_man_svc_attr = vs_man_svc
        return vs_man_svc 
Example #15
Source File: baseutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def _get_wmi_compat_conn(self, moniker, **kwargs):
        # old WMI should be used on Windows / Hyper-V Server 2012 whenever
        # .GetText_ is used (e.g.: AddResourceSettings). PyMI's and WMI's
        # .GetText_ have different results.
        if not BaseUtilsVirt._old_wmi:
            old_wmi_path = "%s.py" % wmi.__path__[0]
            BaseUtilsVirt._old_wmi = imp.load_source('old_wmi', old_wmi_path)
        return BaseUtilsVirt._old_wmi.WMI(moniker=moniker, **kwargs) 
Example #16
Source File: baseutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def _get_wmi_obj(self, moniker, compatibility_mode=False, **kwargs):
        if not BaseUtilsVirt._os_version:
            # hostutils cannot be used for this, it would end up in
            # a circular import.
            os_version = wmi.WMI().Win32_OperatingSystem()[0].Version
            BaseUtilsVirt._os_version = list(map(int, os_version.split('.')))

        if not compatibility_mode or BaseUtilsVirt._os_version >= [6, 3]:
            return wmi.WMI(moniker=moniker, **kwargs)
        return self._get_wmi_compat_conn(moniker=moniker, **kwargs) 
Example #17
Source File: support.py    From CIS-ESP with Apache License 2.0 5 votes vote down vote up
def getDomainName():
	try:
		#get the current computer's (domain controller) domain
		objWMIService = wmi.WMI(computer=".")
		domainResults = objWMIService.ExecQuery("Select Domain from Win32_ComputerSystem")
		domainName = ""
		for result in domainResults:
			domainName = result.Domain
			return domainName
	except:
		return "" 
Example #18
Source File: cis-esp.py    From CIS-ESP with Apache License 2.0 5 votes vote down vote up
def worker(q):
	#importing pythoncom and using CoInitialize() are required to execute WMI commands in threads
	import pythoncom 
	pythoncom.CoInitialize()
	while True:
		host,domainName = q.get() #get the next host from the queue
		runScans(host,domainName) #run the designated scans
		q.task_done() #remove the host from the queue 
Example #19
Source File: client.py    From canisrufus with GNU General Public License v3.0 5 votes vote down vote up
def _detectUsers(self):
        pythoncom.CoInitialize()
        usr = []
        w = wmi.WMI ()
        for user in w.Win32_UserAccount ():
            usr.append('{0};{1};{2}'.format(user.Name, str(AccountType(user.AccountType)).split('.')[1], 'Disabled' if user.Disabled else 'Enabled'))
        return usr 
Example #20
Source File: statemachine.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, params):
        self.params = params
        self.wmi = wmi.WMI()
        self.computer_name = params['computer_name']
        self.output_dir = params['output_dir']
        self.systemroot = params['system_root']
        self.logger = params['logger']
        self.rand_ext = params['rand_ext']
        if 'destination' in params:
            self.destination = params['destination'] 
Example #21
Source File: utils_rawstring.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def get_physical_drives():
    w = wmi.WMI()
    for physical_disk in w.Win32_DiskDrive():
        yield physical_disk.DeviceID, get_physical_drive_size(physical_disk.DeviceID) 
Example #22
Source File: main.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def detect_os():
    c = wmi.WMI()
    version = []
    for c in c.Win32_OperatingSystem():
        version.append(c.Name)
    # name_version = version[0] 
Example #23
Source File: windows_system_profiler.py    From InQRy with MIT License 5 votes vote down vote up
def __init__(self):
        c = wmi.WMI()
        self.win32_bios = c.Win32_BIOS()[0]
        self.win32_processor = c.Win32_Processor()[0]
        self.win32_disk_drive = c.Win32_DiskDrive()
        self.win32_computer_system = c.Win32_ComputerSystem()[0]
        self.win32_computer_system_product = c.Win32_ComputerSystemProduct()[0]
        self.win32_physical_memory = c.Win32_PhysicalMemory()[0] 
Example #24
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def get_table_where(self, tname, where={}):
        try:
            pythoncom.CoInitialize()
            c = WMI()
            f = getattr(c, tname)
            return f(**where)
        finally:
            pythoncom.CoUninitialize() 
Example #25
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def __getattr__(self, attribute):
        """Offer WMI classes as simple attributes. Pass through any untrapped
        unattribute to the underlying OLE object. This means that new or
        unmapped functionality is still available to the module user.
        """
        #
        # Don't try to match against known classes as was previously
        # done since the list may not have been requested
        # (find_classes=False).
        #
        try:
            return self._cached_classes(attribute)
        except pywintypes.com_error:
            return getattr(self._namespace, attribute) 
Example #26
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def query(self, wql, instance_of=None, fields=[]):
        """Perform an arbitrary query against a WMI object, and return
        a list of _wmi_object representations of the results.
        """
        return [_wmi_object(obj, instance_of, fields) for obj in self._raw_query(wql)] 
Example #27
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def instances(self, class_name):
        """Return a list of instances of the WMI class. This is
        (probably) equivalent to querying with no qualifiers::

          wmi.WMI ().instances ("Win32_LogicalDisk")
          # should be the same as
          wmi.WMI ().Win32_LogicalDisk ()
        """
        try:
            return [_wmi_object(obj) for obj in self._namespace.InstancesOf(class_name)]
        except pywintypes.com_error:
            handle_com_error() 
Example #28
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def __init__(self, obj, attributes):
        if attributes:
            for attr in attributes:
                self.__dict__[attr] = obj.Properties_(attr).Value
        else:
            for p in obj.Properties_:
                attr = p.Name
                self.__dict__[attr] = obj.Properties_(attr).Value


#
# class WMI
# 
Example #29
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def new(self, **kwargs):
        """This is the equivalent to the raw-WMI SpawnInstance\_
        method. Note that there are relatively few uses for
        this, certainly fewer than you might imagine. Most
        classes which need to create a new *real* instance
        of themselves, eg Win32_Process, offer a .Create
        method. SpawnInstance\_ is generally reserved for
        instances which are passed as parameters to such
        `.Create` methods, a common example being the
        `Win32_SecurityDescriptor`, passed to `Win32_Share.Create`
        and other instances which need security.

        The example here is `Win32_ProcessStartup`, which
        controls the shown/hidden state etc. of a new
        `Win32_Process` instance::

          import win32con
          import wmi
          c = wmi.WMI ()
          startup = c.Win32_ProcessStartup.new (ShowWindow=win32con.SW_SHOWMINIMIZED)
          pid, retval = c.Win32_Process.Create (
            CommandLine="notepad.exe",
            ProcessStartupInformation=startup
          )

        ..  warning::
            previous versions of this docstring illustrated using this function
            to create a new process. This is *not* a good example of its use;
            it is better handled with something like the example above.
        """
        try:
            obj = _wmi_object(self.SpawnInstance_(), self)
            obj.set(**kwargs)
            return obj
        except pywintypes.com_error:
            handle_com_error()


#
# class _wmi_result
# 
Example #30
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def instances(self):
        """Return a list of instances of the WMI class
        """
        try:
            return [_wmi_object(instance, self) for instance in self.Instances_()]
        except pywintypes.com_error:
            handle_com_error()