def get_pnp_devices_with_drivers(): """Thread Safe WMI Query for list of system devices and installed drivers""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI() try: devices = [] for dev in w.Win32_PnPEntity(): for driver in dev.associators(wmi_result_class='Win32_SystemDriver'): try: devices.append({'caption': dev.Caption, 'hw_id': dev.HardwareID[0], 'name': dev.Name, 'status': dev.Status, 'driverName': driver.Caption, 'driverFile': driver.PathName, 'version': '.'.join([str(x) for x in get_version_number(driver.PathName)]) }) except Exception as ex: print(ex) pass return devices except Exception as e: print(e) finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def memory(): # Reports current memory usage w = WMI('.') result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid()) return int(result[0].WorkingSet) / 1000000.0
def get_current_batteries_info(batteries: list): result = {} if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() try: w = WMI(namespace='WMI') for details in w.BatteryStatus(): for battery in batteries: result[battery] = None if battery == details.InstanceName: result[battery] = { 'Active': details.Active, 'ChargeRate': details.ChargeRate, 'Charging': details.Charging, 'Discharging': details.Discharging, 'DischargeRate': details.DischargeRate, 'PowerOnline': details.PowerOnline, 'Voltage': details.Voltage, 'RemainingCapacity': details.RemainingCapacity } return result except Exception as e: print(e) return None finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def get_legacy_batteries_info(): batteries = [] """Thread Safe WMI Query for remaining battery level""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI() try: for bat in w.Win32_Battery(): b = { "DeviceID":bat.DeviceID, "Availability": bat.Availability, "BatteryStatus":bat.BatteryStatus, "Caption": bat.Caption, "Chemistry": bat.Chemistry, "Description": bat.Description, "DesignVoltage": bat.DesignVoltage, "EstimatedChargeRemaining": bat.EstimatedChargeRemaining, "Status": bat.Status } batteries.append(b) except Exception as e: print(e) batteries.append(-1) finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize() return batteries
def memory_usage_all(): #returns the memory usage of all processes together import os from wmi import WMI w = WMI('.') result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid()) return(result[0].WorkingSet)
def used_memory(): # Get used memory w = WMI('.') result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid()) return int(result[0].WorkingSet)
def GetWindowsService(name: str, usr: str, pword: str, machine='') -> object: from wmi import WMI interface = WMI(computer=machine, user=usr, password=pword) service = interface.Win32_Service(Name=name)[0] assert service, "Service name is invalid" class Service(object): def __init__(self, svc): self.__service = svc return def start(self): rslt, = self.__service.StartService() return True if rslt == 0 else False def stop(self): rslt, = self.__service.StopService() return True if rslt == 0 else False def pause(self): rslt, = self.__service.PauseService() return True if rslt == 0 else False def resume(self): rslt, = self.__service.ResumeService() return True if rslt == 0 else False return Service(service)
def get_nic_list(): ''' Linux返回列表, Windows返回字典 {'WLAN': 'Intel Wireless-n/a/ac 1535 Wireless Network Adapter'} ''' # 获取系统信息 system_name = system() netcard_name = get_netcard_name() if system_name == "Windows": wmi_obj = WMI() data = {} for nic in wmi_obj.Win32_NetworkAdapterConfiguration(): if nic.MACAddress is not None: # 与前面的字典匹配 mac_address = str(nic.MACAddress).replace(':', '-') if mac_address in netcard_name.keys(): net_card_name = netcard_name.get(mac_address) nic_name = str(nic.Caption)[11:] data.update({net_card_name: nic_name}) return system_name, data elif system_name == "Linux": List = list(netcard_name.values()) return system_name, List else: return None
def get_disks_drives(internal_only=True): """Thread Safe WMI Query for Disk drives in Win32_DiskDrive Class Returns: array of Dictionary: {index, model, serial_number, capacity, human_capacity """ disks = [] if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI() wql = 'SELECT * FROM Win32_DiskDrive' if internal_only: wql += ' WHERE InterfaceType <> "USB"' try: for dd in w.query(wql): d = {} d['index'] = dd.Index d['model'] = dd.Caption d['serial_number'] = dd.SerialNumber d['capacity'] = dd.Size d['human_capacity'] = convert_to_human_readable(dd.Size) disks.append(d) return disks except Exception as e: print(e) return None finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def memory(): import os from wmi import WMI w = WMI('.') result = w.query( "SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid()) return int(result[0].WorkingSet)
def _init_windows(self): from wmi import WMI wmi = WMI() os, = wmi.Win32_OperatingSystem() self.distro = os.Caption self.distro_release = os.BuildNumber self.kernel_version = os.Version
def CheckIfRunning(): c = WMI () #iterate through running processes for process in c.Win32_Process (): #if process named dlpc.exe is running if process.Name=="dlpc.exe": return True #if no process that matches name return False
def start(self): """ Start service with WMI :rtype: int """ pythoncom.CoInitialize() c = WMI() for service in c.Win32_Service(Name=self._service_name): retval = service.StartService() return retval[0]
def memory_win(pid): from wmi import WMI #print pid w = WMI('.') result = w.query("SELECT * FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % pid) #print str(result) if not result: return 0 else: return int(result[0].WorkingSet) // (1024*1024) # convert from Bytes to MB
def __init__(self): """ 获取计算机基础信息 """ self.headers_title = {} if sys_platform == "linux": pass elif sys_platform == "win32": self.wmi = WMI()
def cputime_win(pid): from wmi import WMI #print pid w = WMI('.') # result = w.query("SELECT * FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % pid) result = w.query("SELECT * FROM Win32_Process WHERE ProcessId=%d" % pid) #print str(result) if not result: return 0 else: return round((float(result[0].UserModeTime)) / 10000000, 1) # convert to seconds
def get_usage(self): from wmi import WMI w = WMI('.') result = w.query(""" SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d """ % (os.getpid(), )) return int(result[0]['WorkingSet'])
def ProcInfo(self, pid): try: w = WMI('.') result = w.query("SELECT * FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % pid) result_detail = result[0] #process_info= ProcessInformation() self.PrivateWorkingSet = BytesToMB(result_detail.WorkingSetPrivate) return self except Exception, e: print "There was an error getting all the performance related information. See below error code for more info: " print e return False
def get_usage(self): from wmi import WMI w = WMI('.') result = w.query( """ SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d """ % (os.getpid(),)) return int(result[0]['WorkingSet'])
def resident(): if platform.system() == 'Windows': from wmi import WMI w = WMI('.') result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid()) return int(result[0].WorkingSet) else: with open('/proc/%d/status' % os.getpid()) as f: v = f.read() i = v.index('VmRSS:') v = v[i:].split(None, 3) #assert len(v) == 3, v return float(v[1]) * _scale[v[2]]
def get_serial_number(): """Thread Safe WMI Query for Serial Number in Win32_Bios Class""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI() try: for sn in w.Win32_Bios(["SerialNumber"]): return sn.SerialNumber except Exception as e: print(e) return None finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def is_computer_on_AC_power(): """Thread Safe WMI Query return True if AC adapter is connected""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI() try: for bat in w.Win32_Battery(["BatteryStatus"]): return bat.BatteryStatus in [2, 3, 6, 7, 8, 9, 11] except Exception as e: print(e) return None finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def running_services(self, machine_name): """ get a list of running services :param machine_name: string :return: list """ try: machine = WMI(machine_name) for service in machine.Win32_Service(): self.services_running.append(service.Caption) except: return None else: return self.services_running
def get_model(): """Thread Safe WMI Query for Serial Number in Win32_Bios Class""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI() try: for m in w.Win32_ComputerSystem(["Model"]): return m.Model except Exception as e: print(e) return None finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def resident(): if platform.system() == 'Windows': from wmi import WMI w = WMI('.') result = w.query( "SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid()) return int(result[0].WorkingSet) else: with open('/proc/%d/status' % os.getpid()) as f: v = f.read() i = v.index('VmRSS:') v = v[i:].split(None, 3) #assert len(v) == 3, v return float(v[1]) * _scale[v[2]]
def set_display_brightness(brightness): """Thread Safe WMI Query for setting display brightness""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI(namespace="WMI") try: for mon in w.WmiMonitorBrightnessMethods(): mon.WmiSetBrightness(brightness, 0) return True except Exception as e: print(e) return False finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def get_IP(): """Thread Safe WMI Query for get primary IP address""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() try: w = WMI() for m in w.Win32_NetworkAdapterConfiguration(["IPAddress"], IPEnabled=True): return m.IPAddress[0] except Exception as e: print(e) return None finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def is_ssd_drive(disk_id): """Thread Safe WMI Query for checking if disk drive is SSD in MSFT_PhysicalDisk class""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() try: w = WMI(namespace='Microsoft\Windows\Storage') for m in w.MSFT_PhysicalDisk(["MediaType"], DeviceId=disk_id): return int(m.MediaType) == 4 except Exception as e: print(e) return None finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def get_network_adapters(computer: wmi.WMI, *_: Any) -> List[NetworkAdapterModel]: return [ NetworkAdapterModel.from_orm(interface) for interface in computer.Win32_NetworkAdapterConfiguration( IPEnabled=1) ]
def app(): """Open SAPGui""" wmi_obj = WMI() sap_exists = len(wmi_obj.Win32_Process(name='saplgpad.exe')) > 0 if not sap_exists: Popen(['C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplgpad.exe']) while True: try: return GetObject("SAPGUI").GetScriptingEngine except: sleep(1) pass
def get_processors(): """Thread Safe WMI Query for Processors info in Win32_Processor Class""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI() processors = [] try: for p in w.Win32_Processor(["Name"]): processors.append(p.Name) return processors except Exception as e: print(e) return None finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def get_estimated_battery_level(): batteries = [] """Thread Safe WMI Query for remaining battery level""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI() try: for bat in w.Win32_Battery(["EstimatedChargeRemaining"]): batteries.append(bat.EstimatedChargeRemaining) except Exception as e: print(e) batteries.append(-1) finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize() return batteries
def OnCheckin(self, event): self.GetUserInfo() if self.exId not in self.idList: self.exId = self.idList[0] self.userName = self.userList[self.idList.index(self.exId)] checkinDLG = CheckinDialog(self, -1, '用户登录', self.userList) checkinDLG.Center() if checkinDLG.ShowModal() == wx.ID_OK: checkinDLG.Destroy() userName, password = checkinDLG.GetValue() if self.passwordList[self.userList.index(userName)] != password: wx.MessageBox("密码错误,请重新登录!", "信息提示") else: self.cpuId = WMI().Win32_Processor()[0].ProcessorId.strip() self.checkinState = True self.myId = self.idList[self.userList.index(userName)] ourchatDB = MySQL.OurchatDB() ourchatDB.UpdateCPUId(self.myId, self.cpuId) self.kickoutThread = KickOutThread(self, self.myId, self.cpuId) self.Bind(Evt_KICKOUT, self.OnKickout) self.kickoutThread.Start(self.myId, self.cpuId) self.kickoutTimer = wx.PyTimer(self.OnKickoutTimer) self.kickoutTimer.Start(100) if self.myId != self.exId: self.exId = self.myId self.mainConfig.UpdateValue(self.myId, self.exIdTIP, self.exUserList, self.exUserListTIP) self.myName = userName self.myIcon = self.iconList[self.userList.index(userName)] self.statusbar.SetStatusText("%s 已登录" % self.userName, 2) self.CreateWinStruct() self.CreateTopPanel() self.CreateLeftPanel() self.CreateMiddlePanel() self.CreateBottomPanel() self.SetMenuBar(self.checkinMENUBAR)
def get_current_user(computer: wmi.WMI) -> UserModel: for session in computer.Win32_LogonSession(): if session.LogonType != LogonType.interactive: continue user = session.references("Win32_LoggedOnUser")[0] return UserModel.from_orm(user.Antecedent) raise RuntimeError("No interactive logon sessions")
def get_video_cards(): """Thread Safe WMI Query for Video Cards in Win32_VideoController Class""" if not threading.current_thread() is threading.main_thread(): pythoncom.CoInitialize() w = WMI() video_cards = [] try: for v in w.Win32_VideoController(["Caption", "Status"]): video_cards.append({'Caption': v.Caption, 'Status': v.Status}) return video_cards except Exception as e: print(e) return [] finally: if not threading.current_thread() is threading.main_thread(): pythoncom.CoUninitialize()
def get_peak_memory_usage(): os_name = platform.platform(terse=True).lower() if 'windows' in os_name: try: from wmi import WMI w = WMI('.') result = w.query( f'SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process ' f'WHERE IDProcess={os.getpid()}') return int(result[0].WorkingSet) except ImportError: return None try: import resource return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss except ImportError: return None
def getPeakMemoryUsage(cls): """ Return maximum memory usage in kilo bytes. """ if cls.os_family == 'posix': import resource return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss elif cls.os_family == 'nt': from wmi import WMI local_wmi = WMI('.') query = ( u'SELECT PeakWorkingSetSize ' u'FROM Win32_Process ' u'WHERE Handle=%d' % os.getpid()) result = local_wmi.query(query.encode('utf-8')) peak_working_set_size = int(result[0].PeakWorkingSetSize) # FIXME:2099: # Windows XP reports value in bytes, instead of Kilobytes. return int(peak_working_set_size) else: raise AssertionError('OS not supported.')
def WMIQuery(value, mgmtclass): w = WMI('.') result = w.query('SELECT ' + value + ' FROM Win32_' + mgmtclass) return eval('result[0].' + value)
def memory(): import os from wmi import WMI w = WMI('.') result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid()) return str(int(result[0].WorkingSet)/1E9) + ' GB'