def kill(names): print psutil.pids() for name in names: for p in psutil.process_iter(): try: if p.name() == name: p.kill() break except: pass
def test_pid_exists(self): sproc = get_test_subprocess(wait=True) self.assertTrue(psutil.pid_exists(sproc.pid)) p = psutil.Process(sproc.pid) p.kill() p.wait() self.assertFalse(psutil.pid_exists(sproc.pid)) self.assertFalse(psutil.pid_exists(-1)) self.assertEqual(psutil.pid_exists(0), 0 in psutil.pids()) # pid 0 psutil.pid_exists(0) == 0 in psutil.pids()
def test_process_returned(self, tmpdir): """ A new process with a new process ID is created, and the process object is returned. """ old_pids = psutil.pids() process = _run_chroot_process( filesystem=self._create_filesystem_dir(tmpdir), args=['touch', '/example.txt'], ) new_pids = set(psutil.pids()) - set(old_pids) assert process.pid in new_pids
def test_pid_exists_2(self): reap_children() pids = psutil.pids() for pid in pids: try: assert psutil.pid_exists(pid) except AssertionError: # in case the process disappeared in meantime fail only # if it is no longer in psutil.pids() time.sleep(.1) if pid in psutil.pids(): self.fail(pid) pids = range(max(pids) + 5000, max(pids) + 6000) for pid in pids: self.assertFalse(psutil.pid_exists(pid), msg=pid)
def publishData(self): timestamp = time.time() info = {''} if self._pir == None: cpu_use = ps.cpu_percent() users = [u.name for u in ps.users()] nProcesses = len(ps.pids()) memUse = ps.virtual_memory().percent swapUse = ps.swap_memory().percent info = {'count': self._count, 'cpu_usage':cpu_use, 'users':users, 'processes':nProcesses, 'memory_usage':memUse, 'swap_usage':swapUse} else: info = {'count': self._count, 'pir_bool': self._pir.read()} self._count += 1 dataOut = Data(Name(self._dataPrefix).appendVersion(int(timestamp))) dataOut.setContent(json.dumps(info)) dataOut.getMetaInfo().setFreshnessPeriod(10000) self.signData(dataOut) #self._dataCache.add(dataOut) # instead of adding data to content cache, we put data to nfd anyway self.send(dataOut.wireEncode().buf()) print('data name: ' + dataOut.getName().toUri() + '; content: ' + str(info)) # repeat every 1 seconds self.loop.call_later(1, self.publishData)
def capture_system_new_process(process_before_click, new_page_node, gp): list_of_current_processes = psutil.pids() new_processes_after_click = [x for x in list_of_current_processes if x not in process_before_click] print("The new processes found are",new_processes_after_click) details_of_new_process = [] new_process_detected = 0 for new_process in new_processes_after_click: proc = psutil.Process(new_process) details_of_new_process.append(new_process) details_of_new_process.append(proc.name()) details_of_new_process.append(proc.exe()) details_of_new_process.append(proc.cmdline()) details_of_new_process.append(proc.create_time()) details_of_new_process.append(proc.memory_percent()) if len(details_of_new_process) != 0: print("Why am i even here") splitting_of_details_list = [details_of_new_process[x:x+6] for x in range(0, len(details_of_new_process))] new_process_detected = 1 for x in splitting_of_details_list: new_process_node = Node("System Process", name=x[1], PID=x[0], Executable=x[2], Command_line=x[3], Create_time=x[4], Memory_percent=x[5]) gp.create(new_process_node) process_connection = Relationship(new_page_node, "System Process Triggered", new_process_node) gp.create(process_connection) gp.commit() return new_process_detected, gp
def test_zombies(self): # test that NPS is raised by the 2nd implementation in case a # process no longer exists ZOMBIE_PID = max(psutil.pids()) + 5000 for name, _ in self.fun_names: meth = wrap_exceptions(getattr(_psutil_windows, name)) self.assertRaises(psutil.NoSuchProcess, meth, ZOMBIE_PID)
def get_pids(self): ''' Note: Get system process pid. :return: list type [pids......] ''' return psutil.pids()
def pid(self): returnpid = None if not os.path.exists(self.lockfile): return None try: with open(self.lockfile) as lock: pid = lock.read().strip() returnpid = int(pid) except Exception as e: # Error reading pid self.pid = None namepid = self._pid_from_name() if namepid: self.pid = namepid return namepid if returnpid not in psutil.pids(): # No such process self.pid = None namepid = self._pid_from_name() self.pid = namepid return namepid return returnpid
def test_pids(self): # Note: this test might fail if the OS is starting/killing # other processes in the meantime if SUNOS: cmd = ["ps", "ax"] else: cmd = ["ps", "ax", "-o", "pid"] p = get_test_subprocess(cmd, stdout=subprocess.PIPE) output = p.communicate()[0].strip() if PY3: output = str(output, sys.stdout.encoding) pids_ps = [] for line in output.split('\n')[1:]: if line: pid = int(line.split()[0].strip()) pids_ps.append(pid) # remove ps subprocess pid which is supposed to be dead in meantime pids_ps.remove(p.pid) pids_psutil = psutil.pids() pids_ps.sort() pids_psutil.sort() # on OSX ps doesn't show pid 0 if OSX and 0 not in pids_ps: pids_ps.insert(0, 0) if pids_ps != pids_psutil: difference = [x for x in pids_psutil if x not in pids_ps] + \ [x for x in pids_ps if x not in pids_psutil] self.fail("difference: " + str(difference))
def isTaskExist(name): for pid in psutil.pids(): p = psutil.Process(pid) if p.name() == name: print("Task %s exist." % name) return True return False
def data(): ''' Gather data about the local syncthing instance, if any. :maintainer: Andrew Hammond <*****@*****.**> :maturity: new :depends: python-requests,python-psutil :platform: all ''' log = logging.getLogger(__name__) # check to see if syncthing is running before querying. for pid in psutil.pids(): try: p = psutil.Process(pid) except psutil.NoSuchProcess: continue if p.name().startswith('syncthing'): break else: log.debug('Syncthing process not found.') return {} stdata = {} try: for last_path in ['status', 'version']: stdata.update({last_path: _get_syncthing_api('system/' + last_path)}) return {'syncthing': stdata} except requests.exceptions.ReadTimeout: return {}
def xpdf_server_file_dict(): # Make dictionary of the type { xpdf_servername : [ file, xpdf_pid ] }, # to test if the server host file use: # basename(xpdf_server_file_dict().get(server, ['_no_file_'])[0]) == basename(file) # this dictionary always contains the full path (Linux). # TODO: this is not working as I want to: # when the xpdf was opened first without a file it is not visible in the command line # I can use 'xpdf -remote <server> -exec "run('echo %f')"' # where get_filename is a simple program which returns the filename. # Then if the file matches I can just reload, if not I can use: # xpdf -remote <server> -exec "openFile(file)" ps_list = psutil.pids() server_file_dict = {} for pr in ps_list: try: p = psutil.Process(pr) if psutil.version_info[0] >= 2: name = p.name() cmdline = p.cmdline() else: name = p.name cmdline = p.cmdline if name == 'xpdf': try: ind = cmdline.index('-remote') except: ind = 0 if ind != 0 and len(cmdline) >= 1: server_file_dict[cmdline[ind + 1]] = [cmdline[len(cmdline) - 1], pr] except (NoSuchProcess, AccessDenied): pass return server_file_dict
def test_pids(self): # Note: this test might fail if the OS is starting/killing # other processes in the meantime w = wmi.WMI().Win32_Process() wmi_pids = set([x.ProcessId for x in w]) psutil_pids = set(psutil.pids()) self.assertEqual(wmi_pids, psutil_pids)
def process(x): p = psutil.pids() for i in p: pid=psutil.Process(i) name = str(pid.name()) if re.match(x, name): a.append('%i' %i)
def test_pids(self): # Note: this test might fail if the OS is starting/killing # other processes in the meantime if SUNOS or AIX: cmd = ["ps", "-A", "-o", "pid"] else: cmd = ["ps", "ax", "-o", "pid"] p = get_test_subprocess(cmd, stdout=subprocess.PIPE) output = p.communicate()[0].strip() assert p.poll() == 0 if PY3: output = str(output, sys.stdout.encoding) pids_ps = [] for line in output.split('\n')[1:]: if line: pid = int(line.split()[0].strip()) pids_ps.append(pid) # remove ps subprocess pid which is supposed to be dead in meantime pids_ps.remove(p.pid) pids_psutil = psutil.pids() pids_ps.sort() pids_psutil.sort() # on OSX and OPENBSD ps doesn't show pid 0 if OSX or OPENBSD and 0 not in pids_ps: pids_ps.insert(0, 0) self.assertEqual(pids_ps, pids_psutil)
def _no_test_in_process_table(self): """ Make sure the test will be really gone from the process table. """ test_processes = [] old_psutil = False try: process_list = psutil.pids() except AttributeError: process_list = psutil.get_pid_list() old_psutil = True for p in process_list: try: p_obj = psutil.Process(p) if p_obj is not None: if old_psutil: cmdline_list = psutil.Process(p).cmdline else: try: cmdline_list = psutil.Process(p).cmdline() except psutil.AccessDenied: cmdline_list = [] if self.test_module in " ".join(cmdline_list): test_processes.append(p_obj) # psutil.NoSuchProcess happens when the original # process already ended and left the process table except psutil.NoSuchProcess: pass return len(test_processes) == 0
def CheckIfRunning(): Message("Checking if this task is already running...") try: processes=psutil.get_pid_list() except: processes=psutil.pids() for process in processes: if process != os.getpid(): try: ps=psutil.Process(process) try: cmdline=ps.cmdline try: len_cmdline=len(ps.cmdline) except: len_cmdline=len(ps.cmdline()) cmdline=ps.cmdline() if len_cmdline>1: if cmdline[1] == sys.argv[0]: Message("Already running process %s '%s'" % (process,cmdline)) sys.exit(1) except psutil.AccessDenied: Message("I can't read information for process %s" % process) except psutil.NoSuchProcess: Nothing=0
def getSwitchableWindowPid(cmd,commandlineMark): regex = "^(\d+).*"+cmd+".*"+commandlineMark for pid in psutil.pids(): p = psutil.Process(pid) cmdline=str(pid)+" "+str.join(' ', p.cmdline()) #print(cmdline) #print(sys.argv[0]) #if re.search(sys.argv[0],cmdline): if os.getpid()==pid: """we found this script running among processes""" continue match = re.match(regex,cmdline) if match != None: return match.group(1) #_debug(str(pid) + " " +str(p.cmdline())+"\n") #_debug("\nSearching for: '"+regex+"' returned nothing.\n") return None
def __getpids(self): """ This method gets the running pids. :return: An array of running pids """ return psutil.pids()
def wait_until_no_badtest(): bad_test_processes = [] old_psutil = False try: process_list = psutil.pids() except AttributeError: process_list = psutil.get_pid_list() old_psutil = True for p in process_list: try: p_obj = psutil.Process(p) if p_obj is not None: if old_psutil: cmdline_list = psutil.Process(p).cmdline else: cmdline_list = psutil.Process(p).cmdline() if bad_test.path in " ".join(cmdline_list): bad_test_processes.append(p_obj) # psutil.NoSuchProcess happens when the original # process already ended and left the process table except psutil.NoSuchProcess: pass return len(bad_test_processes) == 0
def getSidToken(token_sid): pids = [int(x) for x in psutil.pids() if int(x)>4] for pid in pids: try: hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, False, pid) error=GetLastError() if error!=0: raise WinError(error) hToken = HANDLE(INVALID_HANDLE_VALUE) if not windll.advapi32.OpenProcessToken(hProcess, tokenprivs, byref(hToken)): raise WinError() ##If token SID is the SID of SYSTEM, return the token handle. #print "sid: %s %s"%(pid,GetTokenSid(hToken)) if GetTokenSid( hToken ) == token_sid: print "\t[+] Using PID: " + str(pid) windll.kernel32.CloseHandle(hProcess) return hToken windll.kernel32.CloseHandle(hToken) windll.kernel32.CloseHandle(hProcess) except WindowsError, e : print "[!] Error:" + str(e)
def audit(): """ Check that registered processes are still running. """ if not os.path.exists(register_path): return expected_ps = [] with open(register_path, 'r') as f: for l in f.readlines(): expected_ps.append(_parse_register_line(l)) expected_pids = [pid for pid, pname in expected_ps] running_pids = psutil.pids() missing_pids = set(expected_pids) - set(running_pids) if not missing_pids: return m = Mailer(**conf['mailer']) missing_ps = [(pid, pname) for pid, pname in expected_ps if pid in missing_pids] for pid, pname in missing_ps: subject = 'Missing: {}'.format(pname) body = 'Process [{}] ({}) was expected to be running, but was not found'.format(pname, pid) m.notify(subject, body, conf['mailer']['admins']) deregister(pid)
def envs_and_running_pids(): """ A lock on temporary environments will be held for the life of the generator, so try not to hold on for too long! """ with conda.lock.Locked(conda_execute.config.env_dir): running_pids = set(psutil.pids()) for env in tmp_envs(): exe_log = os.path.join(env, 'conda-meta', 'execution.log') execution_pids = [] with open(exe_log, 'r') as fh: for line in fh: execution_pids.append(line.strip().split(',')) alive_pids = [] newest_pid_time = 0 # Iterate backwards, as we are more likely to hit newer ones first in that order. for pid, creation_time in execution_pids[::-1]: pid = int(pid) # Trim off the decimals to simplify comparisson with pid.create_time(). creation_time = int(float(creation_time)) if creation_time > newest_pid_time: newest_pid_time = creation_time # Check if the process is still running. alive = (pid in running_pids and int(psutil.Process(pid).create_time()) == creation_time) if alive: alive_pids.append(pid) yield env, {'alive_PIDs': alive_pids, 'latest_creation_time': newest_pid_time}
def PROC(): process_list = [] for pid in psutil.pids(): proc_data = {} process = psutil.Process(pid) proc_data['pid'] = pid proc_data['ppid'] = process.ppid() proc_data['name'] = process.name() proc_data['create_time'] = process.create_time() proc_data['status'] = process.status() proc_data['username'] = process.username() proc_data['uids'] = process.uids() proc_data['gids'] = process.gids() proc_data['terminal'] = process.terminal() try: proc_data['exe'] = process.exe() proc_data['num_threads'] = process.num_threads() proc_data['cpu_times'] = process.cpu_times() proc_data['cpu_percent'] = process.cpu_percent() proc_data['memory_percent'] = process.memory_percent() proc_data['is_running'] = process.is_running() except: pass process_list.append(proc_data) save_rsc_file('PROC_LIST', process_list, True)
def update(self): pids = set() for pid in list(psutil.pids()): try: proc = self.procs.get(pid, {}).get('proc') if not proc: proc = psutil.Process(pid) self.procs[pid] = { 'proc': proc, 'pid': pid, 'cmdline': proc.cmdline(), 'create_time': proc.create_time(), 'name': proc.name(), 'username': proc.username(), } self.procs[pid]['cpu_percent'] = proc.cpu_percent() self.procs[pid]['memory_rss'] = proc.memory_info().rss self.procs[pid]['status'] = proc.status() pids.add(pid) except (psutil.NoSuchProcess, psutil.AccessDenied): pass for pid in [p for p in self.procs if p not in pids]: del self.procs[pid] self.data['sort'] = self.sortkey self.data['total'] = len(self.procs) self.data['procs'] = sorted(self.procs.values(), key=lambda p: p[self.sortkey], reverse=True) super(Plugin, self).update()
def run(self): self.processInfo = [] while not self.salir: self.processListLock.acquire() #LOCK lastProcessInfo = self.processInfo self.processInfo = [] pidList = psutil.pids() for pid in pidList: try: pidInfo = psutil.Process(pid) if pidInfo.status() == "zombie": status = pidInfo.status() else: status = "running" self.processInfo.append({"pid": pid, "ppid": pidInfo.ppid(), "command": pidInfo.name(), "status": status}) except psutil.NoSuchProcess: pass # el proceso finalizo en el tiempo que se iteraba en la lista pidList, ignorar except Exception as inst: self.ev.publish("processInfo.error", {"type": type(inst), "traceback": traceback.format_exc()}) addedProcess = [x for x in self.processInfo if x not in lastProcessInfo] removedProcess = [x for x in lastProcessInfo if x not in self.processInfo] self.sendProcessInfo(addedProcess, removedProcess) self.processListLock.release() #LOCK sleep(self.recolectionInterval)
def get_processes_info(self): self.count_processes = len(psutil.pids()) self.count_zombies = 0 self.processes = [] total_mem = psutil.virtual_memory().total for proc in psutil.process_iter(): try: if (proc.status() == psutil.STATUS_ZOMBIE): raise psutil.ZombieProcess(proc.pid) p = process.Process() p.pid = proc.pid p.command = proc.name() p.username = proc.username() p.cpu = proc.cpu_percent(interval=None) p.ram = proc.memory_info().rss p.percent_ram = round(p.ram * 100.0 / total_mem, 2) self.processes.append(p) except psutil.ZombieProcess: # "ZOMBIE ALERT!!" self.count_zombies += 1 except psutil.NoSuchProcess, psutil.AccessDenied: pass
def __get_mul_app(self): loads = [] for load in os.getloadavg(): loads.append(load) cpus = [] for cpu_num, perc in enumerate(psutil.cpu_percent(interval=0.1, percpu=True)): cpus.append({'cpu_num' : cpu_num, 'cpu_percent' : perc}) mul_processes = [] for pid in psutil.pids(): p = psutil.Process(pid) #if 'python' in str(p.cmdline()):#for test if str(p.name()) in mul_app: pstatus = str(p.status()) if str(p.status()) is 'sleeping': pstatus = 'running' mul_processes.append({ 'pname' : str(p.name()), 'virt' : p.get_memory_info().vms, 'res' : p.get_memory_info().rss, 'cpu_percent' : p.get_cpu_percent(interval=0.1), 'p_status' : pstatus, 'mem_percent' : p.get_memory_percent() }) ret = { 'mem_percent' : psutil.phymem_usage().percent, 'load_average' : loads, 'uptime' : str(datetime.now() - datetime.fromtimestamp(psutil.BOOT_TIME)), 'cpus' : cpus, 'mul_process' : mul_processes } self.write(ret)
def run(self): """""" pids = psutil.pids() print pids procs = [] cpu_percent = 0 mem_percent = 0 for pid in pids: p = psutil.Process(pid) if p.name() not in sys_proc: cpu = p.cpu_percent() mem = p.memory_percent() new_proc = Process(p.name, str(p.pid), "not implemented yet", "not yet", str(cpu), str(mem) ) print new_proc procs.append(new_proc) cpu_percent += cpu mem_percent += mem # send pids to GUI wx.CallAfter(Publisher.sendMessage, "update", procs) number_of_procs = len(procs) wx.CallAfter(Publisher.sendMessage, "update_status", (number_of_procs, cpu_percent, mem_percent))
def getCurList(self): return psutil.pids()
# cpu工具 print(psutil.Process) print(psutil.cpu_stats()) # for t in range(10): # print(psutil.cpu_percent(interval=1, percpu=True)) print(psutil.cpu_times()) # 内存工具 print(psutil.virtual_memory()) print(psutil.swap_memory()) # 磁盘工具 print(psutil.disk_partitions()) print(psutil.disk_usage('/')) print(psutil.disk_io_counters()) # 网络工具 print('addr: ', psutil.net_if_addrs()) print('status: ', psutil.net_if_stats()) print(psutil.net_io_counters()) print(psutil.net_connections()) # 进程工具 print(psutil.test()) print(psutil.pids()) p = psutil.Process(1216) print(p.cpu_percent(interval=1)) print(p.cwd()) p.terminate() print(psutil.test())
def find_pids_by_name(p_name): arr = [] for pid in psutil.pids(): if psutil.Process(id).name() == p_name: arr.append(pid) return arr
def pids(): return psutil.pids()
# 获取磁盘信息 print(psutil.disk_partitions()) # 磁盘分区信息 print(psutil.disk_usage('/')) # 磁盘使用情况 psutil.disk_io_counters() # 磁盘IO # 获取网络信息 print(psutil.net_io_counters()) # 获取网络读写字节/包的个数 print(psutil.net_if_addrs()) # 获取网络接口信息 print(psutil.net_if_stats()) # 获取网络接口状态 # 获取当前网络接口状态 print(psutil.net_connections()) # 获取进程信息 print(psutil.pids()) # 所有进程ID p = psutil.Process(3376) #获取指定进程ID,其实就是当前Python交互环境 print(p.name()) # 进程名称 print(p.exe()) # 进程exe路径 print(p.cwd()) #进程工作目录 print(p.cmdline()) # 进程启动的命令行 print(p.ppid()) # 父进程ID print(p.parent()) #父进程 print(p.children()) # 子进程 print(p.status()) # 进程状态 print(p.username()) # 进程用户名 print(p.create_time()) # 进程创建时间 print(p.terminal()) # 进程终端 print(p.cpu_times()) # 进程使用cpu时间 print(p.memory_info()) # 进程使用的内存 print(p.open_files()) # 进程打开的文件
from oauth2client import file, client, tools from gmailworker import mailfunctions # We are going to need to get some emails, so we are going to need some gmail api magic. SCOPES = 'https://mail.google.com/' store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) print('Email Manager\n' 'TechdudeGames Inc.') print('Checking to make sure that MailWatcher is currently off.') for current_pid in psutil.pids(): try: if ('python' in psutil.Process(current_pid).as_dict()['name']) or ( 'MailWatcher' in psutil.Process(current_pid).as_dict()['name']): proc = psutil.Process(current_pid) proc_data = proc.as_dict() if ('MailWatcher' in proc_data['cmdline'][-1]): proc.kill() print('Found MailWatcher, and killed it.') except psutil._exceptions.NoSuchProcess: pass def getmenunumber(minnumber, maxnumber, prompt_text='\nInput:'): keeptrying = True
lista2 = pickle.loads(bytes) titulo = '{:11}'.format("Tamanho") # 10 caracteres + 1 de espaço titulo = titulo + '{:27}'.format("Data de Modificação") titulo = titulo + '{:27}'.format("Data de Criação") titulo = titulo + "Nome" print(titulo) for i in lista2: kb = lista2[i][0] / 1000 tamanho = '{:10}'.format(str('{:.2f}'.format(kb) + ' KB')) print(tamanho, time.ctime(lista2[i][2]), " ", time.ctime(lista2[i][1]), " ", i) time.sleep(1) elif menu == '3': recv = server.recv(2048) redes_formatada(pickle.load(recv)) elif menu == '4': server.send(menu.encode('utf-8')) bytes = server.recv(1024) server.shutdown(socket.SHUT_RDWR) server.close() elif menu == '5': server.send(menu.encode('utf-8')) recv = server.recv(1024) dic = pickle.loads(recv) lista = psutil.pids() time.sleep(2) else: server.close()
def makeindex(self): # DATA E HORA tempo = str(datetime.datetime.now()) print(tempo) # UPTIME with open('/proc/uptime', 'r') as f: uptime_seconds = float(f.readline().split()[0]) uptime_string = str(timedelta(seconds=uptime_seconds)) # print('uptime:', uptime_string) # TIPO DE PROCESSADOR E VELOCIDADE def get_processor_name(): command = "cat /proc/cpuinfo" all_info = subprocess.check_output(command, shell=True).strip() for line in all_info.split("\n"): if "model name" in line: return re.sub(".*model name.*:", "", line, 1) return "" ProcessorData = str(get_processor_name()) # VERSAO DO SISTEMA plataforma = platform.platform() # print('Sistema:', plataforma) #RAM total e utilizada total = str(psutil.virtual_memory().total) used = str(psutil.virtual_memory().used) #cpu usage cpuPercent = psutil.cpu_percent(interval=1) #list #process_names = [proc.name() + proc.name() for proc in psutil.process_iter()] #pid = str(process_names) #proc_names = [for proc in psutil.process_iter(): # proc_names.append(proc.name() + proc.pid())] #pid = str(proc_names) #process = str(psutil.Process().pid) #pids = psutil.pids() #for pid in pids: # process = psutil.Process(pid) #print "%d s" % (pid, process.name(),) #print "%d s" % (pid, process,) #process = psutil.Process(pid) #process_name = process.name() tofile = str() for i in psutil.pids(): tofile = tofile + "<br>" + str(psutil.Process(i).pid) + "-" + str(psutil.Process(i).name()) + "<br>" html_str = """ <!doctype html> <html> <head> <title>Trabalho 1</title> </head> <body> <h1>informacoes basicas sobre o funcionamento do sistema</h1> <p> Data e hora do sistema: """ + tempo + """ </p> <p> Uptime em segundos: """ + uptime_string + """ </p> <p> Processador: """ + ProcessorData + """ </p> <p> Versao do sistema: """ + plataforma + """ </p> <p> Capacidade percentual ocupada do processador: """+ str(cpuPercent) +""" </p> <p> RAM total (MB): """+ total +""" </p> <p> RAM utilizada (MB): """+ used +""" </p> <p> Lista de processos: """ + tofile + """ </p> </body> </html> """ f = open("index2.html", "w") f.write(html_str) f.close() return
try: for proc in psutil.process_iter(attrs=None, ad_value=None): procInfo = proc.as_dict( attrs=['name', 'cpu_percent', 'memory_percent']) procs.append(procInfo) mostCPU = procs[0] mostRAM = procs[0] for p in procs: if p["cpu_percent"] > mostCPU["cpu_percent"]: mostCPU = p if p["memory_percent"] > mostRAM["memory_percent"]: mostRAM = p except (psutil.NoSuchProcess, TypeError, psutil.ProcessLookupError): skipMI = True minProcs = min(minProcs, len(psutil.pids())) topProcs = max(topProcs, len(psutil.pids())) procs = len(psutil.pids()) pidpercent = abs( (((topProcs - procs) - (topProcs - minProcs)) / topProcs) * 100) cpupercent = psutil.getloadavg() cpupercent = transformCPU((sum(cpupercent) / len(cpupercent)) * 10) mempercent = round( (psutil.virtual_memory().used / psutil.virtual_memory().total) * 100, 2) diskpercent = psutil.disk_usage('/').percent tempav, tempsens, tempcol = getTemps() swapfields = [
import psutil import os pids_list = psutil.pids() for i in pids_list: p = psutil.Process(i) try: print(p.children()) except: print("no child")
def check_pid(pid): return int(pid) in psutil.pids() if pid is not None else False
############################ #get disk partitions print("Disk partitions:", psutil.disk_partitions()) #get disk uage print("Disk Usage:", psutil.disk_usage('/')) #get disk IO print("Disk Usage:", psutil.disk_io_counters(perdisk=False)) ############################## # OTHERS ############################# #get users print("Users:", psutil.users()) #Get boot time print("Boot time:", psutil.boot_time()) #Get Pids print("Pids:", psutil.pids()) p = psutil.Process(7152) print("Process details for pid:", p) print("Exe:", p.exe()) print("CWD:", p.cwd()) print("cmdline:", p.cmdline()) print("Parent Process:", p.parent()) print("Parent Process id:", p.ppid()) print("creation time of the Process:", p.create_time()) # there are other features like suspend, terminate ,resume of processes and querying process's memory utilization
def collect_job(): config = utils.get_config() disks = config[utils.DISK_SECTION] interfaces = config[utils.INET_SECTION] account = Account(config[utils.GENERAL_SECTION].get('email'), config[utils.GENERAL_SECTION].get('user_key'), config[utils.GENERAL_SECTION].get('api_key')) report = {} usage = {} net = {} if os.name == 'nt': report['os'] = platform.system() + "-" + platform.win32_ver( )[0] + " " + platform.win32_ver()[2] report['arch'] = platform.architecture()[0] else: report['loadAverage'] = {} if not os.name == 'nt': for idx, la in enumerate(os.getloadavg()): time_la = "1" if idx == 0 else "5" if idx == 2 else "15" report['loadAverage'][time_la] = "{0:.2f}".format(la) if platform.system() == 'Linux': report['os'] = platform.linux_distribution( )[0] + "-" + platform.linux_distribution( )[1] + " " + platform.linux_distribution()[2] report['arch'] = platform.architecture()[0] else: report['os'] = "Mac OS X - " + platform.mac_ver()[0] report['arch'] = platform.architecture()[0] for disk in disks.keys(): if disks[disk] == utils.ENABLED and check_disk(disk): usage_temp = psutil.disk_usage(disk) usage[disk] = { 'total': usage_temp.total, 'used': usage_temp.used, 'free': usage_temp.free, 'percentage': usage_temp.percent } for interf in interfaces.keys(): if interfaces[interf] == utils.ENABLED: net_temp = dict((k.lower(), v) for k, v in psutil.net_io_counters( pernic=True).iteritems())[interf] net[interf] = { 'sent': net_temp.bytes_sent, 'recv': net_temp.bytes_recv } report['inet'] = net report['disks'] = usage report['processes'] = {'value': len(psutil.pids())} report['loadAverage'] = {} if not os.name == 'nt': for idx, la in enumerate(os.getloadavg()): time_la = "1" if idx == 0 else "5" if idx == 2 else "15" report['loadAverage'][time_la] = "{0:.2f}".format(la) report['users'] = {'value': len(psutil.users())} report['uptime'] = str( datetime.now() - datetime.fromtimestamp(psutil.boot_time())).split('.')[0] report['kindDevice'] = 3 api_key = account.api_key url = "%s/%s" % (system_config['ROUTES'].get('collect'), config[utils.GENERAL_SECTION].get('serial')) params = {'apiKey': api_key, 'data': json.dumps(report)} try: response = http.request('POST', url, params, {'user-key': account.user_key}, encode_multipart=False) except Exception, e: console.error("Check your connection") return
import psutil import timeit import time from influxdb import InfluxDBClient db = InfluxDBClient('localhost', 8086, 'root', 'root', 'ProcessorInfo') db.create_database("ProcessorInfo") start = timeit.default_timer() for i in range(1,20): print(i) json_body = [ { "measurement": "records-presentation-final-13", "tags": { "index": i }, "fields": { "cpu_percent_utilization": psutil.cpu_percent(), "number_processes": len(psutil.pids()), "virtual_memory": psutil.virtual_memory()[1], "free_memory": psutil.virtual_memory()[3] } } ] db.write_points(json_body) time.sleep(1) stop = timeit.default_timer() print(f'Time: {stop - start}')
import requests import psutil import time import json url = "http://localhost/stats/add" sleep_time = 3 #in seconds prev_bytes_sent = psutil.net_io_counters().bytes_sent prev_time = time.time() time.sleep(sleep_time) while True: cpu = psutil.cpu_percent(interval=1) processes = len(psutil.pids()) gpu = None memory = psutil.virtual_memory()[2] disk = (psutil.disk_usage('/').total) / (1024 * 1024) network = (psutil.net_io_counters().bytes_sent - prev_bytes_sent) / (time.time() - prev_time) prev_time = time.time() try: r = requests.post(url, json={ "server_name": "server 1", "cpu": cpu, "memory": memory, "network": network, "gpu": gpu, "processes": processes, "disk": disk })
def p2(): global name isok = false pids = psutil.pids() for v in pids: p = psutil.Process(v) if p.name() == name: isok = true if not isok: global path path = '' l2.config(text='你怎么把程序关掉了?') l3.config(text=path) b.config(text='检查', command=iexe) return global ininstall ininstall = true os.kill(pid, SIGTERM) fm.pack_forget() fm2 = tk.Frame(base) fm2.pack() path2 = str(path).replace('\\', '/') + 'garrysmod/addons' l = tk.Label(fm2, text='安装完成会自动关闭程序,请稍后...', font=(getfont(20)), width=50, height=2) l.pack(side='top') l2 = tk.Label(fm2, text='(如果你解压速度过快,可能进度条还没满就会完成)', font=(getfont(16)), width=50, height=2) l2.pack() w = 498 canvas = tk.Canvas(fm2, width=w, height=22, bg='white') canvas.pack() global error error = tk.Label(fm2, font=(getfont(18)), width=50, height=2) error.pack() fill_line = canvas.create_rectangle(1.5, 1.5, 0, 23, width=0, fill='blue') if not os.path.exists(path2): ininstall = false l.config(text='似乎不存在路径,请检查游戏路径!') n = 0 return def unpack(): subprocess.Popen(resource_path('7za.exe') + ' x ' + resource_path('css_content.7z') + ' -o' + path2, shell=True).wait() os._exit(0) run_threaded(unpack) x = 1000 n = w / x for i in range(x): n = n + w / x canvas.coords(fill_line, (0, 0, n, 60)) fm2.update() sleep(0.05)
# coding:UTF-8 import psutil, time, pprint listpid = psutil.pids() totalnum = 0 totalmemery = 0 for n in listpid: process_name = psutil.Process(n).name() process_pencent = psutil.Process(n).memory_percent() print process_name, process_pencent totalnum += 1 totalmemery += psutil.Process(n).memory_percent() print '进程数:', totalnum print '已使用内存:', totalmemery ''' def getProcessInfo(p): """取出指定进程占用的进程名,进程ID,进程实际内存, 虚拟内存,CPU使用率 """ try: cpu = int(p.cpu_percent(interval=0)) rss, vms = p.memory_info() name = p.name pid = p.pid except psutil.NoSuchProcess, e: name = "Closed_Process" pid = 0 rss = 0 vms = 0 cpu = 0 return [name.upper(), pid, rss, vms, cpu]
def _enumerate_processes(): for pid in psutil.pids(): yield (pid, psutil.Process(pid).name())
def num_proc(cls) -> int: return len(psutil.pids())
print('系统总内存', mem.total / 1024 / 1024) # 系统可用内存 print('系统可用内存', mem.available / 1024 / 1024) # 系统总内存 print('系统已用', mem.used / 1024 / 1024) # 系统剩余内存 print('系统剩余内存', mem.free / 1024 / 1024) # 系统buffer print('系统buffer', mem.buffers / 1024 / 1024) # 系统cached print('系统cached', mem.cached / 1024 / 1024) # 系统内存使用率 print('系统内存使用率', mem.percent, '%') # 系统进程 print(psutil.pids().__len__()) # for i in psutil.pids(): # print(psutil.Process(i)) p = psutil.Process(1) print('进程名', p.name()) #进程名 print('进程的bin路径', p.exe()) #进程的bin路径 print('进程的工作目录绝对路径', p.cwd()) #进程的工作目录绝对路径 print('进程状态', p.status()) #进程状态 print('进程创建时间', p.create_time()) #进程创建时间 print('进程uid信息', p.uids()) #进程uid信息 print('进程的gid信息', p.gids()) #进程的gid信息 print('进程的cpu时间信息', p.cpu_times()) #进程的cpu时间信息,包括user,system两个cpu信息 print('进程cpu亲和度', p.cpu_affinity()) #get进程cpu亲和度,如果要设置cpu亲和度,将cpu号作为参考就好 print('进程内存利用率', p.memory_percent()) #进程内存利用率 print('进程内存rss,vms信息', p.memory_info()) #进程内存rss,vms信息 print('进程的IO信息', p.io_counters()) #进程的IO信息,包括读写IO数字及参数
with open(panelPath + '/plugin/encryption365/src/autorenewal.pid', 'r') as f: return f.read() else: return '0' # 主程序入口 def main_process(): # 检查证书签发并完成部署 process_cert_issued() # 检查即将过期的证书并尝试下单续费 process_cert_renewal() # 删除68天之前的日志信息 delete_expired_logs() if __name__ == '__main__': if read_pid() != False and int(read_pid()): pid = int(read_pid()) if pid in psutil.pids(): print("前序任务还未执行完成, 推出: " + str(pid)) else: write_pid() print("新任务开始执行") main_process() else: write_pid() print("新任务开始执行") main_process()
def updater(self): self.speed = ps.cpu_freq() if (not myclass.flag): myclass.flag = 1 #print("in if") try: ## for the first time only to get the name of the cpu p = popen('cat /proc/cpuinfo |grep -m1 "model name"') self.cpuname = p.read().split(':')[1].split('\n')[0] #print(self.cpuname) # cpu name self.cpuInfoLabel.set_text(self.cpuname) self.cpuInfoLabel.set_valign(g.Align.CENTER) p.close() except: print("Failed to get model information") self.cpuCoreLabelValue.set_text(str(ps.cpu_count(logical=False))) self.cpuLogicalLabelValue.set_text(str(self.cpu_logical_cores)) try: p = popen('lscpu|grep -i -E "(vt-x)|(amd-v)"') temp = p.read() if temp: temptext = "Enabled" else: temptext = "Disabled" self.cpuVirtualisationLabelValue.set_text(temptext) p.close() except: print("Failed to get Virtualisation information") try: p = popen('lscpu|grep -i -m1 "L1d cache"') self.cpuL1LabelValue.set_text( sub("[\s]", "", p.read().split(':')[1])) p.close() p = popen('lscpu|grep -i -m1 "L2 cache"') self.cpuL2LabelValue.set_text( sub('[\s]', '', p.read().split(':')[1])) p.close() p = popen('lscpu|grep -i "L3 cache"') self.cpuL3LabelValue.set_text( sub('[\s]', '', p.read().split(':')[1])) p.close() except: print("Failed to get Cache information") self.cpuMxSpeedLabelValue.set_text('{:.2f}'.format(self.speed[2] / 1000) + ' GHz') self.num_of_column_per_row = { 1: 1, 2: 2, 3: 3, 4: 2, 5: 3, 6: 3, 7: 4, 8: 4, 9: 3, 10: 5, 11: 4, 12: 4, 13: 5, 14: 5, 15: 5, 16: 4, 17: 5, 18: 5, 19: 5, 20: 5, 21: 6, 22: 6, 23: 6, 24: 6, 25: 7, 26: 7, 27: 7, 28: 7, 29: 8, 30: 8, 31: 8, 32: 8 } ## logical self.cpu_logical_cores_draw_areas = [] row, column = 0, 0 for cpu_index in range(self.cpu_logical_cores): draw_area = g.DrawingArea() draw_area.set_name(str(cpu_index)) self.cpu_logical_cores_draw_areas.append(draw_area) # draw_area=g.Button(label="begin{0}".format(cpu_index)) if column < self.num_of_column_per_row[self.cpu_logical_cores]: self.logical_cpu_grid.attach(draw_area, column, row, 1, 1) column += 1 else: column = 0 row += 1 self.logical_cpu_grid.attach(draw_area, column, row, 1, 1) column += 1 draw_area.connect('draw', self.on_cpu_logical_drawing) self.logical_cpu_grid.show_all() # return True #print("setting speed") cpuSpeedstring = "{:.2f}".format(self.speed[0] / 1000) + ' Ghz' self.cpuSpeedLabelValue.set_text(cpuSpeedstring) #print("speed setting done") self.cpuUtil = ps.cpu_percent() ## % of the time is is working #print(self.cpuUtil) #print("setting utilisation") cpuUtilString = str(int(self.cpuUtil)) + '%' self.cpuUtilLabelValue.set_text(cpuUtilString) #print('setting utilisation done') #print("setting number of processes and threads") self.cpuProcessesLabelValue.set_text(str(len(ps.pids()))) try: p = popen("ps axms|wc -l") self.cpuThreadsLabelValue.set_text(sub('[\s]', '', p.read())) p.close() except: print("Failed to get Threads") pass try: #cpu package temp temperatures_list = ps.sensors_temperatures() if 'coretemp' in temperatures_list: self.cpuTempLabelValue.set_text( str(int(temperatures_list['coretemp'][0][1])) + ' °C') elif 'k10temp' in temperatures_list: for lis in temperatures_list: if lis.label == 'Tdie': self.cpuTempLabelValue.set_text( str(int(lis.current)) + ' °C') break # cpu fan speed except: pass self.cpuSidePaneLabelValue.set_text(cpuUtilString + ' ' + cpuSpeedstring) ## updating ## cpu utilisation graph if self.update_graph_direction: self.cpuUtilArray.pop(0) self.cpuUtilArray.append(self.cpuUtil) else: self.cpuUtilArray.pop() self.cpuUtilArray.insert(0, self.cpuUtil) temp = ps.cpu_percent(percpu=True) direction = self.update_graph_direction for i in range(self.cpu_logical_cores): if direction: self.cpu_logical_cores_util_arrays[i].pop(0) self.cpu_logical_cores_util_arrays[i].append(temp[i]) else: self.cpu_logical_cores_util_arrays[i].pop() self.cpu_logical_cores_util_arrays[i].insert(0, temp[i]) self.memoryTab() self.disktabUpdate() if len(self.netNameList) != 0: # print('dismis') self.netTabUpdate() if (self.isNvidiagpu == 1): self.gpuTabUpdate() self.sidepaneUpdate() g.Widget.queue_draw(self.cpuDrawArea) for i in range(self.cpu_logical_cores): g.Widget.queue_draw(self.cpu_logical_cores_draw_areas[i]) g.Widget.queue_draw(self.memDrawArea1) g.Widget.queue_draw(self.memDrawArea2) for i in range(0, self.numOfDisks): g.Widget.queue_draw(self.diskWidgetList[i].diskdrawarea1) g.Widget.queue_draw(self.diskWidgetList[i].diskdrawarea2) for i in range(0, self.numOfNets): g.Widget.queue_draw(self.netWidgetList[i].netdrawarea) if (self.isNvidiagpu == 1): g.Widget.queue_draw(self.gpuWidget.gpuutildrawarea) g.Widget.queue_draw(self.gpuWidget.gpuvramdrawarea) g.Widget.queue_draw(self.gpuWidget.gpuencodingdrawarea) g.Widget.queue_draw(self.gpuWidget.gpudecodingdrawarea) ## sidepane g.Widget.queue_draw(self.cpuSidePaneDrawArea) g.Widget.queue_draw(self.memSidePaneDrawArea) for i in range(0, self.numOfDisks): g.Widget.queue_draw( self.diskSidepaneWidgetList[i].disksidepanedrawarea) for i in range(self.numOfNets): g.Widget.queue_draw( self.netSidepaneWidgetList[i].netsidepanedrawarea) if (self.isNvidiagpu == 1): g.Widget.queue_draw(self.gpuSidePaneWidget.gpusidepanedrawarea) return True
def __init__(self, com_port=None, arduino_instance_id=None, log=None): self.backplane_exists = False self.proc_bp = None self.proc_agw = None self.proc_hwg = None # checking running processes. # if the backplane is already running, just note that and move on. for pid in psutil.pids(): p = psutil.Process(pid) if p.name() == "backplane": print("Backplane already running. PID = " + str(p.pid)) self.backplane_exists = True else: continue # if backplane is not already running, start a new instance if not self.backplane_exists: self.proc_bp = subprocess.Popen(['backplane'], stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # new_entry['process'] = self.proc # new_entry['process_id'] = self.proc.pid self.backplane_exists = True print('Backplane is now running') if sys.platform.startswith('win32'): wsgw_start = ['wsgw'] ardgw_start = ['ardgw'] else: wsgw_start = ['xterm', '-e', 'wsgw'] ardgw_start = ['xterm', '-e', 'ardgw'] if log: wsgw_start.append('-l') wsgw_start.append('True') ardgw_start.append('-l') ardgw_start.append('True') if com_port: ardgw_start.append('-c') ardgw_start.append(com_port) if arduino_instance_id: ardgw_start.append('-i') ardgw_start.append(arduino_instance_id) if sys.platform.startswith('win32'): self.proc_agw = subprocess.Popen( wsgw_start, creationflags=subprocess.CREATE_NEW_CONSOLE) self.proc_hwg = subprocess.Popen( ardgw_start, creationflags=subprocess.CREATE_NEW_CONSOLE) else: self.proc_awg = subprocess.Popen(wsgw_start, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) self.proc_hwg = subprocess.Popen(ardgw_start, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # webbrowser.open('https://mryslab.github.io/s3onegpio/', new=1) while True: try: time.sleep(1) except KeyboardInterrupt: self.proc_awg.kill() self.proc_hwg.kill() sys.exit(0)
def get_fan_speed(): return int([x.strip() for x in run([os.path.join(os.path.dirname(os.path.realpath(__file__)), "smcfancontrol/smcFanControl.app/Contents/Resources/smc"), "-f"]).decode().split("\n")][4].split()[-1]) def send(data): payload = { "json": json.JSONEncoder(sort_keys=True).encode(data), "apikey": apikey } r = requests.get(r"https://emoncms.org/input/post.json", params=payload) print("Response: ", r.text) if __name__ == "__main__": a, b, c = os.getloadavg() data = { construct_name(r"uptime-time"): psutil.boot_time(), construct_name(r"load-1min"): a, construct_name(r"load-5min"): b, construct_name(r"load-15min"): c, #construct_name(r"cpu-percent"): psutil.cpu_percent(), #construct_name(r"memory-percent"): psutil.virtual_memory().percent, #construct_name(r"system-disk-percent"): psutil.disk_usage('/').percent, construct_name(r"process-count"): len(psutil.pids()), construct_name(r"cpu-temp"): get_cpu_temp(), construct_name(r"battery-level"): get_battery_level(), construct_name(r"fan-speed"): get_fan_speed() } for k, v in data.items(): print("{} {}={}".format(k.split("-")[1], k.split("-")[2], v))
def _get_pids(): '''python-psutil's API changed in v3.0''' try: return psutil.pids() # v3.0+ except AttributeError: return psutil.get_pid_list() # <= 2.2.1
progBar = tqdm.tqdm(range(size), f"Sending file: {filepath} to server", unit="B", unit_scale=True, unit_divisor=1024) with open(filepath, "rb") as f: for _ in progBar: readBytes = f.read(BUFF_SIZE) if not readBytes: # done break s.send(readBytes) progBar.update(len(readBytes)) print("File sent.") elif int(cmd) == 5: # get Process List processList = psutil.pids() processList = sorted(processList, key=lambda processList: process.pid ) # sort process list by PID s.send(str(len(processList)).encode()) i = 0 while i < len(processList): processStr = psutil.Process(processList[i]) p = str(processStr.pid) + ' ' + processStr.status() + ' ' + processStr.username() + \ ' ' + processStr.name() s.send(p.encode()) i += 1 s.send('done'.encode())
println(psutil.cpu_times()) println(psutil.cpu_times().user) mem = psutil.virtual_memory() println(mem) println(mem.total) partitions = psutil.disk_partitions() println(partitions) println(partitions[1]) println(psutil.disk_usage('/')) println(psutil.net_io_counters()) println(psutil.net_io_counters(pernic=True)) println(psutil.users()) println(psutil.boot_time()) ps = psutil.pids() println(ps) p = psutil.Process(1) println(p.name()) println(p.exe()) println(p.status()) println(p.memory_percent()) #https://pypi.python.org/pypi/psutil
def load_maze(): global mortal_thread_1, Request_for_update, Thread_symbol, Maze_Viewer if Maze_checker(): save_data() #先保存数据 else: return pl = psutil.pids() pid_name = [] for pid in pl: try: pid_name.append(psutil.Process(pid).name()) except: pass #检查该进程是否存在 maze_path = os.path.abspath('Recfiles') command = Algorithm + '\\Maze_' + str( Maze_num_exe ) + '.exe ' + maze_path + '\\Maze_for_c.txt ' + maze_path + '\\answer.txt' Add_logs('[Server]:Send command ' + command + ' to the shell') t = threading.Thread(target=subprocess.call, kwargs={ "args": command, "creationflags": CREATE_NO_WINDOW }) t.start() cols = 0 t.join() save_data() if Thread_symbol == False: #若第一次调用此函数 # mortal_Process_1=multiprocessing.Process(target=Socket_communication) #开启服务器 # mortal_Process_1.start() mortal_thread_1 = threading.Thread(target=Socket_communication) mortal_thread_1.start() Thread_symbol = True if 'MazeViewer.exe' not in pid_name and MazeViewerVail: try: command = str(Maze_Viewer) Process_temp = threading.Thread(target=subprocess.call, kwargs={ 'args': command, "creationflags": CREATE_NO_WINDOW }) #如果进程不存在则启动exe Process_temp.start() Add_logs(command) except: Add_logs('[Server]:Failed to launch the MazeViewer.exe') return else: Request_for_update = True #生成更新请求 Add_logs('[Server]:Request for update') Build_Minecraft_Maze(B)
".")[1] + ", dc=" + domain.split(".")[2] criteria = "(&(&(objectClass=computer)))" attributes = ['dNSHostName', 'Name', 'lastLogonTimestamp'] result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria, attributes) results = [entry for dn, entry in result if isinstance(entry, dict)] return results flag = 0 mypid = os.getpid() #logging function logging.basicConfig(filename='/var/log/ldap_scanning.log', format='%(asctime)s %(message)s', level=logging.DEBUG) #function to checking if script is not already running ( used when script is added to crontab) for pid in psutil.pids(): p = psutil.Process(pid) if (mypid == pid): print("mypid") elif p.name() == "python3" and len( p.cmdline()) > 1 and "CHFLAPS.py" in p.cmdline()[1]: #print ("running") flag = 1 count_sum = 0 if (flag == 0): #else: logging.debug("Script started") try: conn = psycopg2.connect(dbname='ldap',
import psutil as ps from pprint import pprint if __name__ == "__main__": try: """ need privilege """ for proc in ps.process_iter(): print(proc.as_dict()) procs = { p.pid: p.info for p in ps.process_iter(['pid', 'name', 'username', 'cmdline']) } pprint(procs) except Exception as e: print(e) for pid in ps.pids(): try: proc = ps.Process(pid) print(proc.name()) print(proc.username()) print(proc.cmdline()) except Exception as e: print(e)