def DeleteISAPIFilter(filterParams, options): _CallHook(filterParams, "PreRemove", options) server = FindWebServer(options, filterParams.Server) ob_path = server+"/Filters" try: filters = GetObject(ob_path) except pythoncom.com_error as details: # failure to open the filters just means a totally clean IIS install # (IIS5 at least has no 'Filters' key when freshly installed). log(2, "ISAPI filter path '%s' did not exist." % (ob_path,)) return try: assert filterParams.Name.strip("/"), "mustn't delete the root!" filters.Delete(_IIS_FILTER, filterParams.Name) log(2, "Deleted ISAPI filter '%s'" % (filterParams.Name,)) except pythoncom.com_error as details: rc = _GetWin32ErrorCode(details) if rc != winerror.ERROR_PATH_NOT_FOUND: raise log(2, "ISAPI filter '%s' did not exist." % (filterParams.Name,)) # Remove from the load order load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b] if filterParams.Name in load_order: load_order.remove(filterParams.Name) filters.FilterLoadOrder = ",".join(load_order) filters.SetInfo() _CallHook(filterParams, "PostRemove", options) log (1, "Deleted Filter: %s" % (filterParams.Name,))
def RemoveScriptMaps(vd_params, options): "Remove script maps from the already installed virtual directory" parent, name = vd_params.split_path() target_dir = GetObject(FindPath(options, vd_params.Server, parent)) installed_maps = list(target_dir.ScriptMaps) for _map in map(str, vd_params.ScriptMaps): if _map in installed_maps: installed_maps.remove(_map) target_dir.ScriptMaps = installed_maps target_dir.SetInfo()
def CreateISAPIFilter(filterParams, options): server = FindWebServer(options, filterParams.Server) _CallHook(filterParams, "PreInstall", options) try: filters = GetObject(server+"/Filters") except pythoncom.com_error, (hr, msg, exc, arg): # Brand new sites don't have the '/Filters' collection - create it. # Any errors other than 'not found' we shouldn't ignore. if winerror.HRESULT_FACILITY(hr) != winerror.FACILITY_WIN32 or \ winerror.HRESULT_CODE(hr) != winerror.ERROR_PATH_NOT_FOUND: raise server_ob = GetObject(server) filters = server_ob.Create(_IIS_FILTERS, "Filters") filters.FilterLoadOrder = "" filters.SetInfo()
def check_outlook(): wmi = GetObject('winmgmts:') process_outlook = wmi.ExecQuery('select * from Win32_Process where Name="%s"' % "OUTLOOK.EXE") try: if len(process_outlook) == 0: Popen(r"C:\Program Files (x86)\Microsoft Office\Office16\OUTLOOK.EXE") # sle sleep(60) system('tasklist /FI "IMAGENAME eq OUTLOOK.EXE" /FI "STATUS eq running" > outlook.txt') with open('outlook.txt', 'r') as ff: a = ff.readlines() if a[-1].split()[0] == "OUTLOOK.EXE": return 0 else: system("shutdown /r /t 3") except WindowsError: system("shutdown /r /t 3")
def getArchiveDisks(): """ Поиск дисков с архивами. Возвращает: (list) - списко букв дисков, где расположен архив. или исключение WMI """ # Чтение списка жётских дисков на локальном комьпьюетере. all_disk = [] # Все диска компьютера. archive_disk = [] # Список букв дисков с архивом. try: wmi = GetObject('winmgmts:') diskSizeFree = wmi.ExecQuery("SELECT DeviceID FROM Win32_LogicalDisk WHERE DriveType=3") for item in diskSizeFree: all_disk.append(item.Properties_["DeviceID"].Value[0]) except Exception, exc: raise
def clicks(self): wmi = GetObject('winmgmts:/root/cimv2') while 1: processes = wmi.ExecQuery( "Select * from Win32_NTLogEvent where Logfile = 'Application' and EventCode = '20221'" ) self.c = '' for process in processes: a = process.InsertionStrings[5] self.c = a.split('\n')[1].split('\r')[1] break if self.c != '': break self._signal.emit("截获:" + self.c) self.mySignal()
def testit(self): cses = GetObject("WinMgMts:").InstancesOf("Win32_Process") vals = [] for cs in cses: val = cs.Properties_("Caption").Value vals.append(val) assert not (len(vals) < 5), \ "We only found %d processes!" % \ len(vals)
def LoadWebServer(path): try: server = GetObject(path) except pythoncom.com_error, details: msg = details.strerror if exc.excepinfo and exc.excepinfo[2]: msg = exc.excepinfo[2] msg = "WebServer %s: %s" % (path, msg) raise ItemNotFound(msg)
def collect(self): """get the CPU load thanks to WMI""" try: self._count += 1 if self._count >= self._max_count: self._count = 0 #WMI get the load percentage of the machine from win32com.client import GetObject wmi = GetObject('winmgmts:') cpu = wmi.InstancesOf('Win32_Processor') for (_cpu, i) in zip(cpu, xrange(10)): value = _cpu.Properties_('LoadPercentage').Value cpu_usage = int(str(value)) if value else 0 #execute a RPC command for changing the value self._simu.set_values(1, "Cpu", i, (cpu_usage, )) except Exception, excpt: LOGGER.debug("SystemDataCollector error: %s", str(excpt))
def get_workbook(fullname, app_target): """ Returns the COM Application and Workbook objects of an open Workbook. GetObject() returns the correct Excel instance if there are > 1 """ if app_target is not None: raise NotImplementedError('app_target is only available on Mac.') xl_workbook = GetObject(fullname) xl_app = xl_workbook.Application return xl_app, xl_workbook
def __get_system_processes(self): if self.statuses[2] is True: with open(rf"{self.storage_path}\{self.folder}\Processes.txt", "a", encoding="utf-8") as processes: result = [process.Properties_('Name').Value for process in GetObject('winmgmts:').InstancesOf('Win32_Process')] processes.write("\n".join(process for process in result)) processes.close()
def getDiskSizeTotal(diskLeter): """ Определяет размер раздела жёсткого диска. Аргументы: diskLeter - (string) буква раздела жёстка ("c") Возвращает: (int) - общий размер жесткого диска в байтах. """ try: wmi = GetObject('winmgmts:') diskSize = wmi.ExecQuery( "SELECT Size FROM Win32_LogicalDisk WHERE DeviceID='%s:'" % diskLeter) result = int(diskSize[0].Properties_["Size"].Value) except Exception: raise return result
def getDiskSizeFree(diskLetter): """ Определяет размер свободного места на разделе жёсткого диска в байтах. Аргументы: (string) diskLeter - буква раздела жёстка ("c") Возвращает: (int) - размер свободного места жесткого диска в байтах. """ try: wmi = GetObject('winmgmts:') diskSizeFree = wmi.ExecQuery( "SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID='%s:'" % diskLetter) result = int(diskSizeFree[0].Properties_["FreeSpace"].Value) except Exception: raise return result
def __init__ (self, namespace, wmi_class): _wmi_object.__init__ (self, wmi_class) _set (self, "_class_name", wmi_class.Path_.Class) if namespace: _set (self, "_namespace", namespace) else: class_moniker = wmi_class.Path_.DisplayName winmgmts, namespace_moniker, class_name = class_moniker.split (":") namespace = _wmi_namespace (GetObject (winmgmts + ":" + namespace_moniker), False) _set (self, "_namespace", namespace)
def run(self): try: print 'Search video device. Please wait..' self.wmi = GetObject('winmgmts:') self.get_physical_device_object_name() # 2 -- Camera connected but not in use 1 -- Camera is on 0 -- Disconnected if not self.physical_device_object_name: #if device not connected self.status = '0' #return 0 return processes = self.wmi.InstancesOf('Win32_Process') for process in processes: ##for every process: handlers = self.get_handlers(process.Properties_('Name').Value) ##finds handlers if handlers.find(self.physical_device_object_name) > -1: ##checks if any are the webcam self.process_name = process.Properties_('Name').Value ##if do save process name self.process_id = process.Properties_('ProcessId').Value ##save process id break self.status = '1' if self.process_name else '2' ##if the camera is connected but not in a process save status = 2 except Exception as detail: print 'run-time error : ', detail
def steal_process_token_and_spawn(victim_process, new_process): print("[-] work in progress method, do not use. Exiting.") exit(-1) # TODO, not working. DON'T USE. pid = 0 WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') for p in processes: if p.Properties_("Name").Value == victim_process: pid = p.Properties_("ProcessID").Value print(f"[+] Found {victim_process} pid: {pid}") hSystemProcess = win32api.OpenProcess(0x1F0FFF, False, pid) hToken = win32security.OpenProcessToken( hSystemProcess, win32con.TOKEN_QUERY | win32con.TOKEN_DUPLICATE) # fails here when not admin regardless of token privileges of the current process # even with all Se privs, presumably because the current process' DACL is checked during OpenProcessToken print(f"[+] Opened handle to {victim_process} token") print(hToken)
def DeleteISAPIFilter(filterParams, options): _CallHook(filterParams, "PreRemove", options) server = FindWebServer(options, filterParams.Server) ob_path = server + "/Filters" try: filters = GetObject(ob_path) except pythoncom.com_error, details: # failure to open the filters just means a totally clean IIS install # (IIS5 at least has no 'Filters' key when freshly installed). log(2, "ISAPI filter path '%s' did not exist." % (ob_path, )) return
def RemoveDirectory(params, options): if params.is_root(): return try: directory = GetObject(FindPath(options, params.Server, params.Name)) except pythoncom.com_error, details: rc = _GetWin32ErrorCode(details) if rc != winerror.ERROR_PATH_NOT_FOUND: raise log(2, "VirtualDirectory '%s' did not exist" % params.Name) directory = None
def test_getactiveobject(self): print() from win32com.client import GetActiveObject, GetObject # excelApp = GetActiveObject('Excel.Application') excelApp = GetObject(Class='Excel.Application') print(excelApp) import win32process threadId, processId = win32process.GetWindowThreadProcessId( excelApp.Hwnd) print('threadId', threadId) print('processId', processId) # for wb in excelApp.Workbooks: # print('Name', wb.Name) # print('FullName', wb.FullName) # print('Path', wb.Path) # wb.Close() excelApp.Visible = False
def iter_process_by_name(self, name): """ Args: name (str): process name, such as 'alas.exe' Yields: str, str, str: executable_path, process_name, process_id """ from win32com.client import GetObject wmi = GetObject('winmgmts:') processes = wmi.InstancesOf('Win32_Process') for p in processes: executable_path = p.Properties_["ExecutablePath"].Value process_name = p.Properties_("Name").Value process_id = p.Properties_["ProcessID"].Value if process_name == name and process_id != self.self_pid: executable_path = executable_path.replace(r'\\', '/').replace('\\', '/') for folder in self.alas_folder: if folder in executable_path: yield executable_path, process_name, process_id
def check_elevate_process_permission(): WMI = GetObject('winmgmts:') WMI = EnsureDispatch(WMI._oleobj_) elevated = [] processes = WMI.ExecQuery('select * from Win32_Process') for process in processes: if process.Properties_("Name").Value not in ["svchost.exe","lsass.exe","wininit.exe", "System", "services.exe"]: try: if process.ExecMethod_('GetOwner').Properties_("User").Value == None: elevated.append(process.Properties_("Name").Value) except: pass for path in find_paths(elevated): try: name = random_name() check = open(path[0] + "\\%s" % name,"wb") check.close() os.remove(path[0] + "\\%s" % name) print "[VULN] Process %s may be VULNERABLE we have write permission on %s" % (path[1], path[0]) except Exception as e: pass
def __init__(self, file): """Launch editor process""" # let's see if DW's already running # kind of a hack, but... WMI = GetObject('winmgmts:') dwprocesses = WMI.ExecQuery( 'select * from Win32_Process where Name="Dreamweaver.exe"') dwPath = getDWPathFromRegistry() if dwPath is None: raise RuntimeError('Cannot find dreamweaver.exe') processinfo = win32process.CreateProcess( None, '%s %s' % (dwPath, file), None, None, 1, win32process.CREATE_NEW_CONSOLE, None, None, win32process.STARTUPINFO()) if len(dwprocesses): # DW is already running self.pid = dwprocesses[0].Properties_('ProcessId').Value self.hProcess = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, self.pid) else: self.hProcess, nil, self.pid, nil = processinfo
def Uninstall(params, options): _CallHook(params, "PreRemove", options) DeleteExtensionFileRecords(params, options) for vd in params.VirtualDirs: _CallHook(vd, "PreRemove", options) try: directory = GetObject(FindPath(options, vd.Server, vd.Name)) except pythoncom.com_error, details: rc = _GetWin32ErrorCode(details) if rc != winerror.ERROR_PATH_NOT_FOUND: raise log(2, "VirtualDirectory '%s' did not exist" % vd.Name) directory = None if directory is not None: # Be robust should IIS get upset about unloading. try: directory.AppUnLoad() except: exc_val = sys.exc_info()[1] log(2, "AppUnLoad() for %s failed: %s" % (vd.Name, exc_val)) # Continue trying to delete it. try: parent = GetObject(directory.Parent) parent.Delete(directory.Class, directory.Name) except: exc_val = sys.exc_info()[1] log(1, "Failed to remove directory %s: %s" % (vd.Name, exc_val)) _CallHook(vd, "PostRemove", options) log (1, "Deleted Virtual Directory: %s" % (vd.Name,))
def RemoveDirectory(params, options): if params.is_root(): return try: directory = GetObject(FindPath(options, params.Server, params.Name)) except pythoncom.com_error as details: rc = _GetWin32ErrorCode(details) if rc != winerror.ERROR_PATH_NOT_FOUND: raise log(2, "VirtualDirectory '%s' did not exist" % params.Name) directory = None if directory is not None: # Be robust should IIS get upset about unloading. try: directory.AppUnLoad() except: exc_val = sys.exc_info()[1] log(2, "AppUnLoad() for %s failed: %s" % (params.Name, exc_val)) # Continue trying to delete it. try: parent = GetObject(directory.Parent) parent.Delete(directory.Class, directory.Name) log(1, "Deleted Virtual Directory: %s" % (params.Name,)) except: exc_val = sys.exc_info()[1] log(1, "Failed to remove directory %s: %s" % (params.Name, exc_val))
def GetProcessNameEx(pid = None, hwnd = None, fullPath = False): if pid: pass elif hwnd: pid = PyGetWindowThreadProcessId(hwnd)[-1] else: return False try: result = GetObject("winmgmts:").ExecQuery("SELECT * FROM Win32_Process WHERE ProcessID = '" + str(int(pid)) + "'")[0] return result.ExecutablePath.strip('"') if fullPath else result.Name except: return False
class WinProcesses(Win32Processes): def __init__(self): try: self.wmi = GetObject('winmgmts:') except Exception as details: info_string = _utils.formattedException(details=details) print >>sys.stderr, 'WARNING: Unable to access the WMI Object due to the need to be "Run as Administrator". Rerun using the "Run as Administrator" option.' def listProcNames(self): processes = self.wmi.InstancesOf('Win32_Process') return [process.Properties_('Name').Value for process in processes] def pidForProcByName(self,procName=''): p = self.wmi.ExecQuery('select ProcessId from Win32_Process where Name="%s"' % procName) try: return p[0].Properties_('ProcessId').Value except: return -1 def procNamesAndPIDs(self): c = wmi.WMI() return [(process.Name,process.ProcessId) for process in c.Win32_Process()]
def RegSize(): import sys import win32com from win32com.client import GetObject minRegistrySizeMB = 55 if len(sys.argv) > 1: minRegistrySizeMB = int(sys.argv[1]) regObjects = GetObject("winmgmts:").ExecQuery("SELECT CurrentSize FROM Win32_Registry") for regObject in regObjects: if int(regObject.Properties_('CurrentSize')) > minRegistrySizeMB: return False else: return True
def get_hardware_records(self) -> Iterable[dict]: wmi = GetObject('winmgmts:/root/cimv2') device_list = { "CPU 处理器": "Win32_Processor", "主板": "Win32_BaseBoard", "BIOS": "Win32_BIOS", "硬盘": "Win32_DiskDrive", "网卡": "Win32_NetworkAdapter", "内存": "Win32_PhysicalMemory", "电池": "Win32_Battery", "风扇": "Win32_Fan", "IDE": "Win32_IDEController", } for k, v in device_list.items(): for u in wmi.ExecQuery("SELECT * FROM " + v): if u.Caption == u.Name: info = u.Caption try: info = u.Caption + " " + str( int(u.Capacity) / (2**30))[0:3] + "GB" except: try: info = u.Caption + " " + str( int(u.Size) / (2**30))[0:3] + "GB" except: pass else: info = u.Caption + " " + u.Name try: info = u.Caption + " " + u.Name + " " + str( int(u.Capacity) / (2**30))[0:3] + "GB" except: try: info = u.Caption + " " + str( int(u.Size) / (2**30))[0:3] + "GB" except: pass yield {"kind": k, "info": info}
def main(argv): # Change directory this_dir = os.path.abspath(os.path.dirname(__file__)) # os.getcwd() os.chdir(this_dir) WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') # First close all open TimerTool.exe processes (if any) TimerTool_running = True while TimerTool_running: if "TimerTool.exe" in [process.Properties_('Name').Value for process in processes]: subprocess.Popen('TaskKill /F /IM TimerTool.exe') # if it is, kill it! time.sleep(1) processes = WMI.InstancesOf('Win32_Process') else: TimerTool_running = False # If an input parameter is given, start TimerTool.exe and set the resolution if argv: subprocess.Popen(''.join(['TimerTool.exe -t ',str(argv[0]),' -minimized']))
def __process_exists(self, pid): # Need to do different things for *nix vs. Windows # see https://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid-in-python if os.name == 'nt': # only works on windows from win32com.client import GetObject WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') pids = [ process.Properties_('ProcessID').Value for process in processes ] return pid in pids else: # only works on *nix systems try: os.kill(pid, 0) except ProcessLookupError: return False except PermissionError: # errno.EPERM return True # Operation not permitted (i.e., process exists) else: return True # no error, we can send a signal to the process
def kill_scdaemon(): try: # Works for Windows. from win32com.client import GetObject from win32api import OpenProcess, CloseHandle, TerminateProcess WMI = GetObject('winmgmts:') ps = WMI.InstancesOf('Win32_Process') for p in ps: if p.Properties_('Name').Value == 'scdaemon.exe': pid = p.Properties_('ProcessID').Value print "Killing", pid handle = OpenProcess(1, False, pid) TerminateProcess(handle, -1) CloseHandle(handle) except ImportError: # Works for Linux and OS X. pids = subprocess.check_output( "ps ax | grep scdaemon | grep -v grep | awk '{ print $1 }'", shell=True).strip() if pids: for pid in pids.split(): print "Killing", pid subprocess.call(['kill', '-9', pid])
def startNarda(self): """ Opens the EHP200-TS NARDA program. :return: Nothing. """ WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') p_list = [p.Properties_('Name').Value for p in processes] # If program already open, close and restart # Found that this was necessary for a bug-less run if self.ehp200_path.split('\\')[-1] in p_list: self.ehp200_app.connect(path=self.ehp200_path) self.ehp200_app.kill() print("Starting EHP200 program - Connecting...") print( "NOTE: The 'EHP200' program, once open, must be ACTIVE (i.e. the front-most window) for the NS Scan" "Program to connect to it.") self.ehp200_app.start(self.ehp200_path) # Wait until the window has been opened while not pgui.locateOnScreen(self.refpics_path + '/window_title.PNG'): pass print("EHP200 opened successfully.")
def CreateISAPIFilter(filterParams, options): server = FindWebServer(options, filterParams.Server) _CallHook(filterParams, "PreInstall", options) try: filters = GetObject(server+"/Filters") except pythoncom.com_error as exc: # Brand new sites don't have the '/Filters' collection - create it. # Any errors other than 'not found' we shouldn't ignore. if winerror.HRESULT_FACILITY(exc.hresult) != winerror.FACILITY_WIN32 or \ winerror.HRESULT_CODE(exc.hresult) != winerror.ERROR_PATH_NOT_FOUND: raise server_ob = GetObject(server) filters = server_ob.Create(_IIS_FILTERS, "Filters") filters.FilterLoadOrder = "" filters.SetInfo() # As for VirtualDir, delete an existing one. assert filterParams.Name.strip("/"), "mustn't delete the root!" try: filters.Delete(_IIS_FILTER, filterParams.Name) log(2, "Deleted old filter '%s'" % (filterParams.Name,)) except pythoncom.com_error: pass newFilter = filters.Create(_IIS_FILTER, filterParams.Name) log(2, "Created new ISAPI filter...") assert os.path.isfile(filterParams.Path) newFilter.FilterPath = filterParams.Path newFilter.FilterDescription = filterParams.Description newFilter.SetInfo() load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b] if filterParams.Name not in load_order: load_order.append(filterParams.Name) filters.FilterLoadOrder = ",".join(load_order) filters.SetInfo() _CallHook(filterParams, "PostInstall", options, newFilter) log (1, "Configured Filter: %s" % (filterParams.Name,)) return newFilter
def CreateDirectory(params, options): _CallHook(params, "PreInstall", options) if not params.Name: raise ConfigurationError("No Name param") parent, name = params.split_path() target_dir = GetObject(FindPath(options, params.Server, parent)) if not params.is_root(): target_dir = _CreateDirectory(target_dir, name, params) AssignScriptMaps(params.ScriptMaps, target_dir, params.ScriptMapUpdate) _CallHook(params, "PostInstall", options, target_dir) log(1, "Configured Virtual Directory: %s" % (params.Name, )) return target_dir