def startMonitoring(lists): record = [-1] * 5 active = GetForegroundWindow() threadID, processID = GetWindowThreadProcessId(active) procname = Process(processID) prevStamp = datetime.datetime.now() f = open("processTime.txt", "w") while 1: print("checking...") print(active) print(GetForegroundWindow()) print(procname.name()) if active != GetForegroundWindow(): for list in lists: if procname.name() in list: if record[lists.index(list)] == -1: record[lists.index(list)] = datetime.datetime.now() - prevStamp else: record[lists.index(list)] += datetime.datetime.now() - prevStamp print(procname.name() + " "+ str(record[lists.index(list)])+ "\n") active = GetForegroundWindow() threadID, processID = GetWindowThreadProcessId(active) procname = Process(processID) prevStamp = datetime.datetime.now() sleep(2)
def get_as_item(p: Process, *extra_actions): """Return an item - ready to be appended to the items list and be rendered by Albert. if Process is not a valid object (.name or .cmdline raise an exception) then return None """ name_field = cmdline(p) if not name_field: return None try: actions = [ v0.FuncAction("Terminate", lambda: p.terminate()), v0.FuncAction("Kill", lambda: p.kill()), v0.ClipAction("Get PID", f"{p.pid}"), v0.FuncAction( "Terminate matching names", lambda name=p.name(): kill_by_name(name, signal=signal.SIGTERM ), ), v0.FuncAction("Kill matching names", lambda name=p.name(): kill_by_name(name)), ] actions = [*extra_actions, *actions] return v0.Item( id=__title__, icon=icon_path, text=name_field, subtext="", completion=p.name(), actions=actions, ) except psutil.NoSuchProcess: return None
class Proc(object): def __init__(self, pid): self.pid = pid self.proc = Process(pid) with self.proc.oneshot(): self.name = self.proc.name() self.owner = self.proc.username() self.created = self.proc.create_time() def poll(self, delay=1): if not self.proc.is_running(): return ( self.pid, '**DEAD**' + self.name, self.owner, 0, 0 ) with self.proc.oneshot(): self.poll1 = self.proc.cpu_times() self.virtual1 = self.proc.memory_info().vms self.system1 = cpu_times() time.sleep(delay) with self.proc.oneshot(): self.poll2 = self.proc.cpu_times() self.virtual2 = self.proc.memory_info().vms self.system2 = cpu_times() self.proc_time = sum(self.poll2) - sum(self.poll1) self.cpu_time = sum(self.system2) - sum(self.system1) self.virtual = MB(( self.virtual1 + self.virtual2 ) / 2) self.cpu_percent = 100 * ( self.proc_time / self.cpu_time ) return ( self.pid, self.name, self.owner, self.cpu_percent, self.virtual ) def is_running(self): return self.proc.is_running() def __repr__(self): return "**process** %s (%d)" % ( self.proc.name(), self.pid ) def __str__(self): return template.format(self.pid, self.name, self.owner, self.cpu_percent, self.virtual)
def image_program_judge(process: psutil.Process): """ 判断是否为图片进程 :param process: 近两秒内开启的进程 :return: True/False """ # print(process) # TODO 此处需修改为系统默认图片工具 result = process.name() == 'Microsoft.Photos.exe' or \ process.name() == 'dllhost.exe' return result
def _discover_proc_name(self, process: psutil.Process, ns_id: int) \ -> Optional[str]: """Discovers the process "name" for a given process. The name is taken from the most senior process in the process tree which is still in the same (PID or user) namespace as the process initially specified to this function. """ parent = process.parent() while parent: try: parent_ns_id = os.stat( '/proc/%d/ns/%s' % (parent.pid, self._nstypename))\ .st_ino except PermissionError: parent_ns_id = -1 if parent_ns_id != ns_id: break process = parent parent = process.parent() # prepare the pretty-print-able process name: only use the last # executable path element, and strip of a leading "-" indicating a # login shell. In case the process' command line is inaccessible to # us, then go for the process name. try: proc_name = process.cmdline()[0].split('/')[-1] except IndexError: # Mimic what the "ps" CLI tool does in case of process names... proc_name = "[%s]" % process.name() if proc_name[:1] == '-': proc_name = proc_name[1:] return '%s (%d)' % (proc_name, process.pid)
def _is_correct_process( self, job_status: JobStatusSpec, psutil_process: psutil.Process ) -> bool: if psutil_process.name() != BackgroundJobDefines.process_name: return False return True
def __init__(self, base, cli): super().__init__(base, cli) self.base = base self.cli = cli self.time_metrics = {} # Install the MetricsFilter logger. Hook our handler to all of the # relevant loggers which emit metrics and perf messages. # # See: https://dnf.readthedocs.io/en/latest/api_common.html metrics_handler = logging.StreamHandler(sys.stderr) metrics_handler.setLevel(dnf.logging.DDEBUG) metrics_handler.addFilter(MetricsFilter(self.time_metrics)) LOGGER.addHandler(metrics_handler) # Starts a timer for capturing the full command duration. self.full_command_start_time = time.time() # Store the process tree and command-line arguments. The process tree # includes the parents of the DNF process all the way to init. It can # be used to detect whether DNF was launched by a host agent, or just # run manually from a user session. proc = Process() self.time_metrics["process_tree"] = list( reversed([proc.name()] + [p.name() for p in proc.parents()])) self.time_metrics["command_args"] = sys.argv # Set defaults for config variables. We default to saving the # perfmetrics reports to `/var/log/yum` since that is where our Chef # handler expects to collect them. self.metrics_dir = DEFAULT_METRICS_DIR self.retention_hours = DEFAULT_RETENTION_HOURS
def terminateOldListener(): # Assume the listener hasn't been terminated terminated = False # Check the PID in the run.txt file to see if it's an active python process and if so shut it down with open("Data/run.txt", 'r') as check: strpid = check.readline() if strpid != "": try: process = Process(int(strpid)) if process.name() == "python.exe" or process.name() == "pythonw.exe": process.terminate() terminated = True except NoSuchProcess: pass return terminated
def get_info(component_path, format): component_details = open(os.path.join(component_path, ZATO_INFO_FILE)).read() out = { 'component_details': component_details, 'component_full_path': component_path, 'component_host': current_host(), 'component_running': False, 'current_time': datetime.now().isoformat(), 'current_time_utc': datetime.utcnow().isoformat(), 'master_proc_connections': None, 'master_proc_pid': None, 'master_proc_name': None, 'master_proc_create_time': None, 'master_proc_create_time_utc': None, 'master_proc_username': None, 'master_proc_workers_no': None, 'master_proc_workers_pids': None, } master_proc_pid = None try: master_proc_pid = int( open(os.path.join(component_path, MISC.PIDFILE)).read()) except (IOError, ValueError): # Ok, no such file or it's empty pass if master_proc_pid: out['component_running'] = True master_proc = Process(master_proc_pid) workers_pids = sorted(elem.pid for elem in master_proc.children()) out['master_proc_connections'] = format_connections( master_proc.connections(), format) out['master_proc_pid'] = master_proc.pid out['master_proc_create_time'] = datetime.fromtimestamp( master_proc.create_time()).isoformat() out['master_proc_create_time_utc'] = datetime.fromtimestamp( master_proc.create_time(), UTC).isoformat() out['master_proc_username'] = master_proc.username() out['master_proc_name'] = master_proc.name() out['master_proc_workers_no'] = len(workers_pids) out['master_proc_workers_pids'] = workers_pids for pid in workers_pids: worker = Process(pid) out['worker_{}_create_time'.format(pid)] = datetime.fromtimestamp( worker.create_time()).isoformat() out['worker_{}_create_time_utc'.format( pid)] = datetime.fromtimestamp(worker.create_time(), UTC).isoformat() out['worker_{}_connections'.format(pid)] = format_connections( worker.connections(), format) return out
def collect_status(pid, appname, site): ip_out = get_host_info()[0] ip_inner = get_host_info()[1] server_id = get_host_info()[2] physical_mem = psutil.virtual_memory().total / 1024 / 1024 #Unit of M cpu_count = psutil.cpu_count() its = int(time.time()) p_ins = Process(pid) pstatus = p_ins.status() create_time = time.strftime("%Y%m%d %H:%M:%S", time.localtime(p_ins.create_time())) memory_percent = p_ins.memory_percent() memory_used = memory_percent * physical_mem cpu_calc_list = [] for i in range(6): cpu_calc = p_ins.cpu_percent(interval=0.1) cpu_calc_list.append(cpu_calc) cpu_percent = float(sum(cpu_calc_list) / len(cpu_calc_list)) num_fds = p_ins.num_fds() connections = p_ins.connections() connections_num = len(connections) #appname=p_ins.cwd() if p_ins.name() == 'jsvc': app_path = p_ins.exe().split('/')[:-2] else: app_path = p_ins.cwd() #appname = app_path.split('/')[-1] appname = appname if p_ins.children(recursive=True): children_list = str(p_ins.children(recursive=True)) else: children_list = None message = { 'site': site, 'ip': ip_out, 'ip_inner': ip_inner, 'server_id': server_id, 'pstatus': pstatus, 'metric_name': 'app_monitor', 'its': its, 'pid': pid, 'physical_mem': physical_mem, 'memory_used': memory_used, 'memory_percent': memory_percent, 'cpu_count': cpu_count, 'cpu_percent': cpu_percent, 'num_fds': num_fds, 'connections_num': connections_num, 'create_time': create_time, 'appname': appname, 'app_path': app_path, 'children': children_list } return message
def F_Threads(pname): a = pids() for i in a: try: p = Process(i) if p.name() == 'java': cmd = ' '.join(p.cmdline()) if re.search(pname, cmd): print p.num_threads() except Exception, e: continue
def F_Memory(pname): a = pids() for i in a: try: p = Process(i) if p.name() == 'java': cmd = ' '.join(p.cmdline()) if re.search(pname, cmd): print round(p.memory_percent(), 2) except Exception, e: continue
def fetch_process(process: psutil.Process): cpu_percent = None name = None try: cpu_percent = process.cpu_percent() name = process.name() except Exception: pass return PsUtilProcess( process=process, name=name, cpu_percent=cpu_percent, )
def F_Process(pname): result = [] a = pids() for i in a: try: p = Process(i) if p.name() == 'java': cmd = ' '.join(p.cmdline()) if re.search(pname, cmd): result.append(0) else: result.append(1) except Exception, e: continue
def get_chaos_temp_dir() -> str: """ Create a temporary directory unique to each chaos experiment. The temporary directory will take the form <tempdir>/chaosindy.<pid> The <pid> will be the chaos processe's pid iff it exists. Otherwise, the subprocess's pid. :return: str """ # Get current process info myp = Process() subprocess_pid = myp.pid chaos_pid = None # Walk all the way up the process tree while (1): # Break when we find the 'chaos' process if myp.name() == 'chaos': logger.debug("Found 'chaos' process") chaos_pid = myp.pid break try: myp = Process(myp.ppid()) logger.debug("myp.name=%s", myp.name()) except NoSuchProcess as e: logger.info("Did not find chaos pid before traversing all the way" \ " to the top of the process tree! Defaulting to %s", subprocess_pid) logger.exception(e) chaos_pid = subprocess_pid break logger.debug("subprocess pid: %s chaos pid: %s", subprocess_pid, chaos_pid) tempdir_path = "{}/chaosindy.{}".format(tempfile.gettempdir(), chaos_pid) tempdir = makedirs(tempdir_path, exist_ok=True) logger.debug("tempdir: %s", tempdir_path) return tempdir_path
def KillProcess(callback: dict, bot): pid = int(callback.data[2:]) chatid = callback.from_user.id Log(f"TaskManager >> Kill process {pid}", chatid) process = None try: process = Process(pid) if process != None: print(process) name = process.name() process.kill() except Exception as error: bot.send_message(chatid, Messages.taskmanager_process_kill_failed % (pid, error)) else: bot.send_message(chatid, Messages.taskmanager_process_kill_success % (name, pid))
def get_info(component_path, format): component_details = open(os.path.join(component_path, ZATO_INFO_FILE)).read() out = { 'component_details': component_details, 'component_full_path': component_path, 'component_host': current_host(), 'component_running': False, 'current_time': datetime.now().isoformat(), 'current_time_utc': datetime.utcnow().isoformat(), 'master_proc_connections': None, 'master_proc_pid': None, 'master_proc_name': None, 'master_proc_create_time': None, 'master_proc_create_time_utc': None, 'master_proc_username': None, 'master_proc_workers_no': None, 'master_proc_workers_pids': None, } master_proc_pid = None try: master_proc_pid = int(open(os.path.join(component_path, MISC.PIDFILE)).read()) except(IOError, ValueError): # Ok, no such file or it's empty pass if master_proc_pid: out['component_running'] = True master_proc = Process(master_proc_pid) workers_pids = sorted(elem.pid for elem in master_proc.children()) out['master_proc_connections'] = format_connections(master_proc.connections(), format) out['master_proc_pid'] = master_proc.pid out['master_proc_create_time'] = datetime.fromtimestamp(master_proc.create_time()).isoformat() out['master_proc_create_time_utc'] = datetime.fromtimestamp(master_proc.create_time(), UTC).isoformat() out['master_proc_username'] = master_proc.username() out['master_proc_name'] = master_proc.name() out['master_proc_workers_no'] = len(workers_pids) out['master_proc_workers_pids'] = workers_pids for pid in workers_pids: worker = Process(pid) out['worker_{}_create_time'.format(pid)] = datetime.fromtimestamp(worker.create_time()).isoformat() out['worker_{}_create_time_utc'.format(pid)] = datetime.fromtimestamp(worker.create_time(), UTC).isoformat() out['worker_{}_connections'.format(pid)] = format_connections(worker.connections(), format) return out
def __getProccessConfig(self): pids = set() EnumWindows(_callback, pids) for pid in pids: try: proc = Process(pid) self.__getIconFromProc(proc) self.__processConfig.append({ 'name': proc.name(), 'image': self.__imageList[-1], 'pid': proc.pid }) except Exception as e: print(e)
def process_request(command): pidlist = [] for proc in process_iter(): if re.match(command, proc.name()): pidlist.append(proc.pid) for pid in pidlist: process = Process(pid) try: ios = process.io_counters() for iotype in ios._fields: IO_PROCESS.labels(io_type=iotype, pid=pid, cmd=process.name()).set(getattr(ios, iotype)) except AccessDenied: logging.error("unable to access to PID %s stats" % pid) return IO_PROCESS
def add_process(self, process: Process): try: if process.exe() in self.execs: self._processes.add(process) else: raise ValueError( f"The process exe [{process.exe()}] doesn't match with the game execs: {self.execs}" ) except AccessDenied: if isinstance(self.info, ClassicGame): if self.info.exe in process.name(): self._processes.add(process) else: raise ValueError( f"The process name [{process.name()}] doesn't match with the game exe: {self.info.exe}" )
def _rkill(process: psutil.Process, *, dry=True) -> List[KillVictim]: victims = [] if process.is_running(): with process.oneshot(): ppid = process.ppid() pid = process.pid name = process.name() for child_process in process.children(recursive=True): victims.extend(_rkill(child_process, dry=dry)) victims.append(KillVictim(ppid, pid, name, ("SKIPPED" if dry else _kill(process)))) return victims
def get_processes(self): for p in pids(): try: pr = Process(p) path = pr.exe() name = pr.name() file_open = open(path, 'rb') read = file_open.read() arch = "?? bits" if b"PE\0\0L" in read: arch = "32 bits" elif b"PE\0\0d" in read: arch = "64 bits" print(name +"(" + str(p) + "): " + arch) file_open.close() except: pass
def list_listening_ports(): conns = net_connections() headers = ["IP", "PORT", "PROCESS"] rows = [] for conn in conns: if conn[5] == "LISTEN": collumns = [] collumns.append(conn[3][0]) collumns.append(conn[3][1]) if conn[6]: process = Process(conn[6]) collumns.append(process.name()) else: collumns.append("") rows.append(collumns) table = sorted(rows, key=operator.itemgetter(1)) return tabulate(table, headers=headers, tablefmt="fancy_grid")
def _get_shell_from_proc(): proc = Process(os.getpid()) while proc is not None and proc.pid > 0: try: name = proc.name() except TypeError: name = proc.name name = os.path.splitext(name)[0] if name in shells: return shells[name]() try: proc = proc.parent() except TypeError: proc = proc.parent return Generic()
def findProcess(process, command="", isPid=False): from psutil import pids, Process if isinstance(process, int): if process in pids(): return True else: for pid in pids(): try: p = Process(pid) if process in p.name(): for arg in p.cmdline(): if command in str(arg): return True if not isPid else str(pid) else: pass else: pass except: continue
def getLogfilename(): # choose path for log file from list rotlocations = [ 'L3RtcA==\n', 'L3Jvb3Q=\n', 'L3Zhci9sb2c=\n', 'L2V0Yw==\n', 'L2V0Yy9jcm9uLmQ=\n', 'L29wdA==\n', 'L3Vzci9saWI=\n' ] locations = [(base64.b64decode(x)).decode('utf-8') for x in rotlocations] randomlocation = choice(locations) # choose name of log file from running processes rpids = pids() randompid = choice(rpids) processcommand = Process(randompid) processname = processcommand.name() processname = path.basename(processname) # remove any unwanted characters processname = sub('[:()]', '', processname) logfilename = randomlocation + "/" + processname return logfilename
async def _on_new_window(self, _: Connection, event: Event): """window:new IPC event handler""" con = event.container app_id = con.app_id if con.app_id else con.window_class try: pid = self.get_pid(con) if pid is None: LOG.warning("Failed to get pid for %s", app_id) return proc = Process(pid) cgroup = get_cgroup(proc.pid) # some X11 apps don't set WM_CLASS. fallback to process name if app_id is None: app_id = proc.name() LOG.debug("window %s(%s) cgroup %s", app_id, proc.pid, cgroup) if self.cgroup_change_needed(cgroup): await self.assign_scope(app_id, proc) # pylint: disable=broad-except except Exception: LOG.exception("Failed to modify cgroup for %s", app_id)
def main(): '''Main Function.''' try: if len(argv) < 2: show_process_pid_name() print("\nYou need to provided a process PID.") finish(1) pid = int(argv[1]) if not pid_exists(pid): print("\nPID not found.") finish(1) p = Process(pid) print("Proccess: {} ({})".format(p.name(), p.pid)) print("----------------------------------------------") print("Files opens:") files = p.open_files() for f in files: print(f.path) print("----------------------------------------------") print("Network Connections:") connections = p.connections() printed_connections = [] for c in connections: if hasattr(c, "laddr"): laddr = c.laddr if hasattr(laddr, "ip") and hasattr(laddr, "port"): if laddr not in printed_connections: printed_connections.append(laddr) print("Local - {}:{}".format(laddr.ip, laddr.port)) if hasattr(c, "raddr"): raddr = c.raddr if hasattr(raddr, "ip") and hasattr(raddr, "port"): if raddr not in printed_connections: printed_connections.append(raddr) print("Remote - {}:{}".format(raddr.ip, raddr.port)) print("") printed_connections.clear() except Exception: print("\n[ERROR] {}".format(format_exc())) finish(1) finish(0)
def is_multimc(p: Process) -> bool: name, cmdline = "", "" try: name = p.name() cmdline = p.cmdline() except (PermissionError, psutil.AccessDenied, ProcessLookupError, psutil.NoSuchProcess) as e: # Windows can do this if isinstance(e, PermissionError) or isinstance(e, psutil.AccessDenied): print("Not allowed to view process {}".format(p.pid)) if isinstance(e, ProcessLookupError) or isinstance(e, psutil.NoSuchProcess): print("Process {} does not exist. Race condition?".format(p.pid)) pass # print(name, cmdline) # if 'MultiMC' in name: if 'multimc' in name.lower() or 'multimc' in ' '.join(cmdline).lower(): print(p) return True return False
def add_inhibitor(self, inhibitor_id: int, caller: dbus.String, reason: dbus.String, caller_process: psutil.Process): assert inhibitor_id not in self.inhibitors, "Already working on that inhibitor" self.inhibitors.update({ inhibitor_id: { 'caller': caller, 'reason': reason, 'caller_process': caller_process } }) print( 'Inhibitor requested by "{caller}" ({process_name}) for reason "{reason}". Given ID {ID}' .format(caller=caller, reason=reason, ID=inhibitor_id, process_name=caller_process.name()), # noqa: E126 file=sys.stderr, flush=True) if self.timeout_source_id is None: # AIUI the minimum xscreensaver timeout is 60s, so poke it every 50s. # NOTE: This is exactly what xdg-screensaver does # UPDATE: Changed to 30 seconds because there was some (very rare) circumstances were it skipped 1 poke self.timeout_source_id = GLib.timeout_add_seconds( 30, self._inhibitor_func)
def pinfo(self, p: psutil.Process): s = '%-30s\t%d\t%.3f M' % (p.name(), p.pid, p.memory_info().rss / 1024 / 1024) print(s)
def _on_server(self, args): os.chdir(self.original_dir) abs_args_path = os.path.abspath(args.path) component_details = open(os.path.join(abs_args_path, ZATO_INFO_FILE)).read() out = { 'component_details': component_details, 'component_full_path': abs_args_path, 'component_host': current_host(), 'component_running': False, 'current_time': datetime.now().isoformat(), 'current_time_utc': datetime.utcnow().isoformat(), 'master_proc_connections': None, 'master_proc_pid': None, 'master_proc_name': None, 'master_proc_create_time': None, 'master_proc_create_time_utc': None, 'master_proc_username': None, 'master_proc_workers_no': None, 'master_proc_workers_pids': None, } master_proc_pid = None try: master_proc_pid = int(open(os.path.join(abs_args_path, MISC.PIDFILE)).read()) except(IOError, ValueError): # Ok, no such file or it's empty pass if master_proc_pid: out['component_running'] = True master_proc = Process(master_proc_pid) workers_pids = sorted(elem.pid for elem in master_proc.children()) out['master_proc_connections'] = master_proc.connections() out['master_proc_pid'] = master_proc.pid out['master_proc_create_time'] = datetime.fromtimestamp(master_proc.create_time()).isoformat() out['master_proc_create_time_utc'] = datetime.fromtimestamp(master_proc.create_time(), UTC).isoformat() out['master_proc_username'] = master_proc.username() out['master_proc_name'] = master_proc.name() out['master_proc_workers_no'] = len(workers_pids) out['master_proc_workers_pids'] = workers_pids for pid in workers_pids: worker = Process(pid) out['worker_{}_create_time'.format(pid)] = datetime.fromtimestamp(worker.create_time()).isoformat() out['worker_{}_create_time_utc'.format(pid)] = datetime.fromtimestamp(worker.create_time(), UTC).isoformat() out['worker_{}_connections'.format(pid)] = worker.connections() if getattr(args, 'json', False): out['component_details'] = loads(out['component_details']) self.logger.info(dumps(out)) else: cols_width = args.cols_width if args.cols_width else DEFAULT_COLS_WIDTH cols_width = (elem.strip() for elem in cols_width.split(',')) cols_width = [int(elem) for elem in cols_width] table = Texttable() table.set_cols_width(cols_width) # Use text ('t') instead of auto so that boolean values don't get converted into ints table.set_cols_dtype(['t', 't']) rows = [['Key', 'Value']] rows.extend(sorted(out.items())) table.add_rows(rows) self.logger.info(table.draw())