Ejemplo n.º 1
0
 def run(self):
     running = True
     cpu = []
     mem = []
     x = []
     z = []
     d = 0.0
     p = self.proc
     i0 = []
     i1 = []
     i2 = []
     i3 = []
     try:
         while d < self.totaltime:
             d += 1
             if p.status != 'zombie':
                 # If the program is running, this captures
                 # the vital-statistics.
                 cpu.append(p.get_cpu_percent())
                 mem.append(p.get_memory_percent())
                 z.append(p.get_cpu_times().system)
                 x.append(d)
                 i0.append([p.get_io_counters()[0]])
                 i1.append([p.get_io_counters()[1]])
                 i2.append([p.get_io_counters()[2]])
                 i3.append([p.get_io_counters()[3]])
             else:
                 # This watches and ensures that the
                 # process is indeed dead. This is the first
                 # level of exception handling and
                 # loop-breakage.
                 procs = psutil.get_process_list()
                 gone, alive = psutil.wait_procs(procs,
                                                 3,
                                                 callback=on_terminate)
                 break
             time.sleep(1)
     except psutil._error.AccessDenied:
         # This exception watches for the natural death of the
         # process. This is the second level of redundancy handling
         # the death of the task, the first one is in the else
         # statement above.
         p.kill()
         print "It has died and has become a... " + p.status
         procs = psutil.get_process_list()
         gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
     except KeyboardInterrupt:
         # This exception allows the user to exit the watch. You
         # have to terminate the process elsewhere.
         print "Exiting..." + p.status
         procs = psutil.get_process_list()
         gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
     self.cpu = pl.array(cpu)
     self.x = pl.array(x)
     self.ram = pl.array(mem)
     self.z = pl.array(z)
     self.i0 = pl.array(i0)
     self.i1 = pl.array(i1)
     self.i2 = pl.array(i2)
     self.i3 = pl.array(i3)
Ejemplo n.º 2
0
	def run(self):
		running=True;
		cpu = [];
		mem = [];
		x = [];
		z = []
		d = 0.0;
		p = self.proc;
		i0 = []; 
		i1 = [];
		i2 = [];
		i3 = [];
		try:
			while d<self.totaltime:
				d += 1;
				if p.status!='zombie':
					# If the program is running, this captures
					# the vital-statistics.
					cpu.append(p.get_cpu_percent());
					mem.append(p.get_memory_percent());
					z.append(p.get_cpu_times().system)
					x.append(d)
					i0.append([p.get_io_counters()[0]])
					i1.append([p.get_io_counters()[1]])
					i2.append([p.get_io_counters()[2]])
					i3.append([p.get_io_counters()[3]])
				else:
					# This watches and ensures that the
					# process is indeed dead. This is the first
					# level of exception handling and
					# loop-breakage. 
					procs = psutil.get_process_list();
					gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
					break
				time.sleep(1)
		except psutil._error.AccessDenied:
			# This exception watches for the natural death of the
			# process. This is the second level of redundancy handling
			# the death of the task, the first one is in the else
			# statement above. 
			p.kill()
			print "It has died and has become a... "+p.status;
			procs = psutil.get_process_list();
			gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
		except KeyboardInterrupt:
			# This exception allows the user to exit the watch. You
			# have to terminate the process elsewhere. 
			print "Exiting..."+p.status
			procs = psutil.get_process_list();
			gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
		self.cpu = pl.array(cpu);
		self.x = pl.array(x);
		self.ram = pl.array(mem);
		self.z = pl.array(z);
		self.i0 = pl.array(i0);
		self.i1 = pl.array(i1);
		self.i2 = pl.array(i2);
		self.i3 = pl.array(i3);
Ejemplo n.º 3
0
def get_processes(sort_by_name=True, cmdline=False):
    if cmdline:
        processes = [(p.pid, p.name, p.cmdline)
                     for p in psutil.get_process_list()]
    else:
        processes = [(p.pid, p.name) for p in psutil.get_process_list()]
    if sort_by_name:
        return sorted(processes, lambda t1, t2: (cmp(t1[1], t2[1]) or
                                                 cmp(t1[0], t2[0])))
    else:
        return sorted(processes, lambda t1, t2: (cmp(t1[0], t2[0]) or
                                                 cmp(t1[1], t2[1])))
Ejemplo n.º 4
0
 def machine_poweron(self, listset):
     try:
         #如果因为不能使用Console对象而无法进行关机则需要使用强制结束进程的方法,所以在开机时需要查询开机后对应的VirtualBox.exe进程的PID号
         #查询运行虚拟机前已有的VirtualBox.exe进程的PID号
         p_list = psutil.get_process_list()
         Old_VirtualBoxPidSet = []
         for p in p_list:
             str_p = str(p)
             pid_re = re.compile('VirtualBox', re.I)
             if pid_re.search(str_p):
                 Old_VirtualBoxPidSet.append(
                     str_p.split('pid=')[1].split(',')[0])
         Old_VirtualBoxPidSet = set(Old_VirtualBoxPidSet)
         #开始启动虚拟机
         Imachine = self.vbox.FindMachine(listset[1])
         LocalSession = client.Dispatch("VirtualBox.Session")
         Imachine.LockMachine(LocalSession, self.vboxCnst.LockType_Write)
         #把Localsession储存至类中的session字典中,以虚拟机名字为值
         self.SessionDict[listset[1]] = LocalSession
         Imachine_mutable = LocalSession.Machine
         MachineConsole = LocalSession.Console
         # if MachineConsole is not None:
         #     MachineConsole.PowerUp()
         # else:
         LocalSession.UnlockMachine()
         Imachine.LaunchVMProcess(LocalSession, "gui", '')
         #虚拟机启动完成
         #查询运行虚拟机后所有的VirtualBox.exe进程的PID号
         p_list = psutil.get_process_list()
         New_VirtualBoxPidSet = []
         for p in p_list:
             str_p = str(p)
             pid_re = re.compile("VirtualBox.exe", re.I)
             if pid_re.search(str_p):
                 New_VirtualBoxPidSet.append(
                     str_p.split('pid=')[1].split(',')[0])
         New_VirtualBoxPidSet = set(New_VirtualBoxPidSet)
         #集合相减,得到此次运行虚拟机而产生的VirtualBox.exe的进程的PID号
         PID_List = New_VirtualBoxPidSet - Old_VirtualBoxPidSet
         result = [
             'success',
             listset[0],
             listset[1],
         ]
         for pid in PID_List:
             result.append(pid)
         result.append(listset[len(listset) - 1])
         return result
     except BaseException, e:
         result = ['failure', listset[0], listset[1], str(e)]
         print(str(e))
         return result
Ejemplo n.º 5
0
def get_proc_by_pid(pid):
	proc = [];
	procs = psutil.get_process_list()
	for p in procs:
		if pid == p.pid:
			proc.append(p);
	return proc
Ejemplo n.º 6
0
    def _find_proc(self, service):
        """Returns the pid of a given service running on this machine.

        service (ServiceCoord): the service we are interested in
        returns (psutil.Process): the process of service, or None if
                                  not found

        """
        logger.debug("ResourceService._find_proc")
        cmdline = config.process_cmdline[:]
        length = len(cmdline)
        for i in range(length):
            if config.installed:
                cmdline[i] = cmdline[i].replace("%s", service.name)
            else:
                cmdline[i] = cmdline[i].replace(
                    "%s",
                    os.path.join(
                        ResourceService.SERVICE_PATH[service.name],
                        service.name))
            cmdline[i] = cmdline[i].replace("%d", str(service.shard))
        for proc in psutil.get_process_list():
            try:
                if proc.cmdline[:length] == cmdline:
                    self._services_prev_cpu_times[service] = \
                        proc.get_cpu_times()
                    return proc
            except psutil.NoSuchProcess:
                continue
        return None
Ejemplo n.º 7
0
def reposync_is_running():
    proclist = psutil.get_process_list()
    for p in proclist:
        for arg in p.cmdline():
            if os.path.basename(arg) == 'repo_sync':
                return True
    return False
Ejemplo n.º 8
0
def terminate():
    """
    + Remove mongo db under '/tmp';
    + Kill any process that has '__PYCON2013_DEMO3_PROCESS__' defined in its environ;
    """
    import psutil   as py_psutil;
    import glob     as py_glob;
    import os       as py_os;
    import commands as py_commands;

    # Remove db ...
    for f in py_glob.glob('/tmp/demoDB*'):
        try:
            py_os.unlink(f);
        except:
            continue;

    # Remove stale processes ...
    for proc in py_psutil.get_process_list():
        try:
            if (proc.name not in ('python', 'mongod')):
                continue;
            if (not filter((lambda x: 
                            (x.split('=')[0] == '__PYCON2013_DEMO3_PROCESS__')),
                           open('/proc/%(pid)s/environ' % dict(pid = proc.pid)).read().split('\x00'))):
                continue;
        except IOError,    e:
            continue;
        except ValueError, e:
            continue;
def PrintRunningProcesses():
    processes = psutil.get_process_list()
    processes = sorted(processes, key=lambda process: process.name)

    print 'List of running processes:\n'
    for process in processes:
        print process.name
Ejemplo n.º 10
0
    def memory_st(self):
        #self.mem_stats = {
        #"MBytes_available": (int(self.stats_dict['SMA.s0.g_space'])/1024/1024),
        #"MBytes_allocated": (int(self.stats_dict['SMA.s0.c_bytes'])/1024/1024)
        #}
	import re
	# Get memory of varnishd from default file on ubuntu
	varnishdefault = open('/etc/default/varnish','r')
	for line in varnishdefault:
		if re.search('^VARNISH_STORAGE_SIZE' ,line):
			totalmem = line.split('=')[1][:-2]
			#print "Total Memory Asigned: " + totalmem

	import psutil
	ps = psutil.get_process_list()
	for p in ps:
		if p.name == "varnishd" and p.ppid != 1:
			varnishpid = p.pid
	i = psutil.Process(varnishpid)
	meminfo = i.get_memory_info()
	memusage = i.get_memory_info()[0]

	self.mem_stats = {
			"MBytes_available": int(totalmem),
			"MBytes_allocated": int(memusage)/1024/1024
			}

        return self.mem_stats
Ejemplo n.º 11
0
    def __init__(self, tunnel_cmd):
        """Opens an ssh tunnel as defined by the tunnel_cmd

        Args:
          tunnel_cmd (str): tunnel_cmd
          E.g. "ssh -fN -L 1231:localhost:2345 [email protected]"
        """

        self.tunnelcmd = tunnel_cmd
        ssh_process = subprocess.Popen(tunnel_cmd,
                                       universal_newlines=True,
                                       shell=True,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT,
                                       stdin=subprocess.PIPE)
        while True:
            p = ssh_process.poll()
            if p is not None: break
            time.sleep(1)
        if p == 0:
            current_username = psutil.Process(os.getpid()).username()
            ssh_processes = [
                proc for proc in psutil.get_process_list()
                if proc.cmdline() == tunnel_cmd.split()
                and proc.username() == current_username
            ]
            if len(ssh_processes) == 1:
                self.pid = ssh_processes[0]
            else:
                raise RuntimeError, 'multiple (or zero?) tunnel ssh processes found: ' + str(
                    ssh_processes)
        else:
            raise RuntimeError, 'Error creating tunnel: ' + str(
                p) + ' :: ' + str(ssh_process.stdout.readlines())
Ejemplo n.º 12
0
def getpid():
	x = r'iTunes[^H]'
	p = psutil.get_process_list()
	for r in p:
		aa = str(r)
		if re.findall(x,aa):
			return aa.split('pid=')[1].split(',')[0]
Ejemplo n.º 13
0
def is_server_running():
    """Get a list of running tmsi_server processes"""
    try:
        procs = [p for p in psutil.get_process_list() if 'tmsi_server' in p.name]
        return procs
    except psutil.NoSuchProcess as e:
        return False
Ejemplo n.º 14
0
def reposync_is_running():
    proclist = psutil.get_process_list()
    for p in proclist:
        for arg in p.cmdline():
            if os.path.basename(arg) == 'repo_sync':
                return True
    return False
Ejemplo n.º 15
0
    def done(self):

        server = {}
        # Get system variables
        # =======================================================================
        # server['load_average']  = os.getloadavg()
        #
        # server['total_virtmem'],server['used_virtmem'] = swapinfo()
        # server['total_phymem'], server['avail_phymem'], server['used_phymem']   = meminfo()
        # server['cpu_count'], server['cpu_percent']   = cpuinfo()
        # server['disks'] = diskinfo()
        # =======================================================================
        server["iostat"] = iostat()

        # Get process list
        f_processes = []

        processes = psutil.get_process_list()
        processes = filter(lambda x: not x.pid == 0, processes)
        # processes.sort(key=lambda x: x.get_cpu_times())
        # processes.reverse()
        for p in processes:
            try:
                f_processes.append([p.name, p.get_cpu_times(), p.get_memory_percent(), time.ctime(p.create_time)])
            except:
                pass

        server["processes"] = f_processes

        return server
Ejemplo n.º 16
0
def getpid(process_name):
    p_list=psutil.get_process_list()
    for x in p_list:
      if process_name in str(x):
        return x.pid
      else:
        return 0
def TerminateIfVMwareIsRunning():
    # Make sure VMware is not running so the update doesn't conflict with in memory settings
    for proc in psutil.get_process_list():
        if proc.name()=='vmware-vmx' or proc.name()=='VMware Fusion':
            print "VMware is currently running.\nPlease exit before updating VMware paths and settings."
            print
            sys.exit()
Ejemplo n.º 18
0
def create_tunnel(tunnel_cmd):
    ssh_process = subprocess.Popen(tunnel_cmd,
                                   universal_newlines=True,
                                   shell=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.STDOUT,
                                   stdin=subprocess.PIPE)

    # Assuming that the tunnel command has "-f" and "ExitOnForwardFailure=yes", then the
    # command will return immediately so we can check the return status with a poll().

    while True:
        p = ssh_process.poll()
        if p is not None: break
        time.sleep(1)

    if p == 0:
        # Unfortunately there is no direct way to get the pid of the spawned ssh process, so we'll find it
        # by finding a matching process using psutil.

        current_username = psutil.Process(os.getpid()).username
        ssh_processes = [
            proc for proc in psutil.get_process_list()
            if proc.cmdline == tunnel_cmd.split()
            and proc.username == current_username
        ]

        if len(ssh_processes) == 1:
            return ssh_processes[0]
        else:
            raise RuntimeError, 'multiple (or zero?) tunnel ssh processes found: ' + str(
                ssh_processes)
    else:
        raise RuntimeError, 'Error creating tunnel: ' + str(p) + ' :: ' + str(
            ssh_process.stdout.readlines())
def PrintRunningProcesses():
  processes = psutil.get_process_list()
  processes = sorted(processes, key=lambda process: process.name)

  print 'List of running processes:\n'
  for process in processes:
    print process.name
Ejemplo n.º 20
0
def getpid():
    x = r'iTunes[^H]'
    p = psutil.get_process_list()
    for r in p:
        aa = str(r)
        if re.findall(x, aa):
            return aa.split('pid=')[1].split(',')[0]
Ejemplo n.º 21
0
def get_process_list(*args, **kwargs):
    processList = []
    for process in psutil.get_process_list(*args, **kwargs):
        #intercept the object and rewrap it in a nicer implementation.
        try: processList.append(IPsutilProcess(process))
        except: continue
    return processList
Ejemplo n.º 22
0
def processinfo(x):
    p=psutil.get_process_list()
    for r in p:
        aa = str(r)
        f=re.compile(x,re.I)
        if f.search(aa):
            print aa.split('pid=')
def TerminateIfVMwareIsRunning():
    # Make sure VMware is not running so the update doesn't conflict with in memory settings
    for proc in psutil.get_process_list():
        if proc.name() == 'vmware-vmx' or proc.name() == 'VMware Fusion':
            print "VMware is currently running.\nPlease exit before updating VMware paths and settings."
            print
            sys.exit()
Ejemplo n.º 24
0
def processInfo(x):
    p = psutil.get_process_list()
    for r in p:
        aa = str(r)
        f = re.compile(x, re.i)
        if f.search(aa):
            print aa.split('pid=')
def create_logfile(logPath='/Program Files'):
    if not os.path.exists(logPath):
        os.mkdir(logPath)
    punctuator='-'*90 + '\n'
    format1='%s  %s %s %s %s %s'
    #   print ('Press q to quit the logging session. Any other key to continue.')
    inp=''
    c=0
    while inp!='q':
        proc=ps.get_process_list()
        print (proc)
        # proc=sorted(proc, key=lambda proc: proc.name)
        c+=1
        log_file_name=logPath + '/' + 'log_file.log' + str(c) #% int(time.time())
        f=open(log_file_name, 'a')
        f.write(punctuator)
        f.write(time.ctime() + "\n")
        f.write(format1 % ("NAME",  "RSS", "VMS", "%CPU", "%MEM", "%NET"))
        f.write("\n")

        for p in proc:
            name=p.name
          #  path=p.path
            rss, vms=p.get_memory_info()
            rss=str(rss)
            vms=str(vms)
            cpu_usage=p.get_cpu_percent()
            mem_usage=p.get_memory_percent()
            connections=p.connections()
            f.write(format1 % (name, rss, vms, cpu_usage, mem_usage, connections))
            f.write("\n")
        f.close()
        print ('Done with logging.')
        time.sleep(5)
Ejemplo n.º 26
0
def reposync_is_running():
    proclist = psutil.get_process_list()
    for p in proclist:
        for arg in p.cmdline:
            if os.path.split(arg)[1] == 'repo_sync':
                return True
    return False
Ejemplo n.º 27
0
def reposync_is_running():
    proclist = psutil.get_process_list()
    for p in proclist:
        for arg in p.cmdline:
            if os.path.split(arg)[1] == 'repo_sync':
                return True
    return False
Ejemplo n.º 28
0
	def java_running(self):
		'''
		Get all running processes on system.
		Parsed all running processes for specific
		java process.  If java process running, returns
		amount of memory utilization java process is using
		at query time.
		if Java is not running, returns tuple with error code
		and string notifying java not running.
		'''
		try:
			## Change This Process Name To What You Want.
			process_name = 'java.exe'
			all_proc_list, found_proc = [], []

			for proc in p.get_process_list():
				proc_info = proc.as_dict(attrs=['name','memory_percent'])
				all_proc_list.append(proc_info)
				
			for proc_attr in all_proc_list:
				if proc_attr['name'] == process_name:
					found_proc.append(proc_attr)
					break
			
			if len(found_proc)>0:
				for proc in found_proc:
					mem_used = str(round(proc['memory_percent'], 2)) + "%"
					proc_data = {'process_name': process_name,'mem_used': mem_used}
					return proc_data
					
			else:
				return int(8), str("Java Process Not Running.")
						
		except Exception, error:
			return int(9), str(error)
Ejemplo n.º 29
0
def get_python_processes():
    def is_python_process(p):
        try:
            return 'python' in p.name
        except:
            return false

    return len([p for p in psutil.get_process_list() if is_python_process])
Ejemplo n.º 30
0
 def checkProcess(self):
     rtn = []
     for x in get_process_list():
         # If the process is java, and the commandline args included elastic search...
         if x.name() == 'java' and self.process in x.cmdline():
             # ...add pid to list
             rtn.append(x.pid)
     return rtn
Ejemplo n.º 31
0
def getpid(key):
    key=key.strip()
    for i in psutil.get_process_list():
        if len(i.cmdline()) > 0 and i.cmdline()[0].find('java') != -1:
            for c in i.cmdline():
                if c.find(key) != -1:
                    return i.pid
    return 0
def memorypercent():
	try: import psutil
	except: return 0.0
	mem = 0.0
	for p in psutil.get_process_list():
		try:mem += p.get_memory_percent()
		except: pass
	return mem
Ejemplo n.º 33
0
def processinfo(processName):
    pids = psutil.get_process_list()
    for pid in pids:
        strPid = str(pid)
        f = re.compile(processName, re.I)
        if f.search(strPid):
            zabbixPid = strPid.split('pid=')[1].split(',')[0]
            return zabbixPid
Ejemplo n.º 34
0
def getRunProcessesCount():
    processes = psutil.get_process_list()
    runProcessesCount = 0
    for proc in processes:
        match = re.match(runnerName, proc.name)
        if (match != None):
            runProcessesCount += 1
    return runProcessesCount
Ejemplo n.º 35
0
def processinfo(x):
    p = psutil.get_process_list()
    for r in p:
        aa = str(r)
        f = re.compile(x, re.I)
        if f.search(aa):
            # print aa.split('pid=')[1].split(',')[0]
            print(aa.split('pid=', 2))
Ejemplo n.º 36
0
def processinfo(processName):
                    pids = psutil.get_process_list()
                    for pid in pids:
                        strPid = str(pid)
                        f = re.compile(processName,re.I)
                        if f.search(strPid):
                            zabbixPid = strPid.split('pid=')[1].split(',')[0]  
                            return zabbixPid
Ejemplo n.º 37
0
def getpid(key):
    key = key.strip()
    for i in psutil.get_process_list():
        if len(i.cmdline()) > 0 and i.cmdline()[0].find('java') != -1:
            for c in i.cmdline():
                if c.find(key) != -1:
                    return i.pid
    return 0
Ejemplo n.º 38
0
	def run(self):
		running=True;
		cpu = [];
		mem = [];
		x = [];
		z = []
		d = 0.0;
		p = self.proc;
		try:
			while d<self.totaltime:
				d += 1;
				if p.status=='running':
					# If the program is running, this captures
					# the vital-statistics.
					cpu.append(p.get_cpu_percent());
					mem.append(p.get_memory_percent());
					z.append(p.get_cpu_times().system)
					x.append(d)
				else:
					# This watches and ensures that the
					# process is indeed dead. This is the first
					# level of exception handling and
					# loop-breakage. 
					procs = psutil.get_process_list();
					gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
					break
				time.sleep(1)
		except psutil._error.AccessDenied:
			# This exception watches for the natural death of the
			# process. This is the second level of redundancy handling
			# the death of the task, the first one is in the else
			# statement above. 
			p.kill()
			print "It has died and has become a... "+p.status;
			procs = psutil.get_process_list();
			gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
		except KeyboardInterrupt:
			# This exception allows the user to exit the watch. You
			# have to terminate the process elsewhere. 
			print "Exiting..."+p.status
			procs = psutil.get_process_list();
			gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
		self.cpu = pl.array(cpu);
		self.x = pl.array(x);
		self.ram = pl.array(mem);
		self.z = pl.array(z);
Ejemplo n.º 39
0
Archivo: main.py Proyecto: bneg/genesis
    def get_ui(self):
        ui = self.app.inflate('taskmgr:main')
        l = psutil.get_process_list()
        l = sorted(l, key=self.sort_key)
        if self._sort[1]:
            l = reversed(l)

        for x in l:
            try:
                ui.append('list', UI.DTR(
                    UI.Image(file='/dl/core/ui/stock/service-%s.png'%('run' if x.is_running() else 'stop')),
                    UI.Label(text=str(x.pid)),
                    UI.Label(text=str(int(x.get_cpu_percent()))),
                    UI.Label(text=str(int(x.get_memory_percent()))),
                    UI.Label(text=x.username),
                    UI.Label(text=x.name),
                    UI.TipIcon(
                        icon='/dl/core/ui/stock/info.png',
                        id='info/%i'%x.pid,
                        text='Info'
                    )
                ))
            except:
                pass

        hdr = ui.find('sort/'+self._sort[0])
        hdr.set('text', ('↑ ' if self._sort[1] else '↓ ')+ hdr['text'])

        if self._info is not None:
            try:
                p = filter(lambda x:x.pid==self._info, l)[0]
                iui = self.app.inflate('taskmgr:info')
                iui.find('name').set('text', '%i / %s'%(p.pid,p.name))
                iui.find('cmd').set('text', ' '.join("'%s'"%x for x in p.cmdline))
                iui.find('uid').set('text', '%s (%s)'%(p.username,p.uids.real))
                iui.find('gid').set('text', str(p.gids.real))
                iui.find('times').set('text', ' / '.join(str(x) for x in p.get_cpu_times()))
                if p.parent:
                    iui.find('parent').set('text', p.parent.name)
                    iui.find('parentinfo').set('id', 'info/%i'%p.parent.pid)
                else:
                    iui.remove('parentRow')

                sigs = [
                    (x, getattr(signal, x))
                    for x in dir(signal)
                    if x.startswith('SIG')
                ]

                for x in sigs:
                    iui.append('sigs', UI.SelectOption(
                        text=x[0], value=x[1]
                    ))
                ui.append('main', iui)
            except:
                pass

        return ui
Ejemplo n.º 40
0
def processinfo(x):
    x = x.strip()
    name = None
    p = psutil.get_process_list()
    for r in p:
        r = str(r)
        if re.search('pid=' + x, r):
            name = re.search("name='(.*)'", r).group(1)
    return name
Ejemplo n.º 41
0
Archivo: proc.py Proyecto: jul/dsat
def proc(ctx, payload, msg):
    res= dict()

    sum_file = dict()
    procc= dict()
    sum_connection = dict() 
    percent_mem= dict()
    all_proc = psutil.get_process_list()
    carbon_measure = dict()
    interesting = { 
        '/usr/lib/firefox/firefox', '/opt/google/chrome/chrome', 'mysqld', 
        'mongod', "ping.py", "clock.py", "orchester.py", 
        "proc.py", "master.py", "tracker.py","cpu.py", "rrd.py", "csvw.py"}
    for x in all_proc:
        try:
            key = ( set(x.cmdline()) & interesting) and "me" or "other"
            carbon_key=None
            cmd = x.cmdline()
            intersect =  interesting &set(cmd)
            if intersect:
                assert len(intersect) == 1
                carbon_key = intersect.pop()
                
            try:
                procc += dict({key : 1 })
            except:
                pass


            try:
                sum_file += dict({key :x.get_num_fds()})
            except:
                pass

            try:
                sum_connection += dict({ key: sum(x.get_num_ctx_switches())})
            except:
                pass
            try:
                percent_mem += dict({key : x.get_memory_percent() })
                if carbon_key:
                    carbon_measure += { carbon_key: x.get_memory_percent() }
            except:
                pass
        except NoSuchProcess:
            pass 
    try:
        send(carbon_measure)
    except Exception as e:
        ctx.log.error('Carbon is not very liking that %r' % e)
    ratio = lambda d : min(1,1.0 *d.get("me", 0)/max(.0001,d.get("other",0)))
    absol = lambda d : d.get("me", 0) + d.get("other", 0)
    res=dict(sum_file= sum_file, percent_mem= percent_mem, all_proc =len(all_proc))
    res["data"] = map(ratio, [ sum_file, sum_connection, percent_mem, procc])
    res["data"] += map(absol, [sum_file, sum_connection, percent_mem, procc])
    del all_proc
    return res
Ejemplo n.º 42
0
    def process(self, data, historys):
        """插件方法,必须实现
        data是最新的计数数据,caches是最近的数据"""
        process_list = psutil.get_process_list()
        for rule in self.rules:
            if not self._isrun(process_list, rule.patt):
                return self._get_send_data(rule)

        return None
Ejemplo n.º 43
0
 def get_PID(self):
     ###
     # return the system PID for 'aria2c'  process
     ###
     proc_list = psutil.get_process_list()
     for proc in proc_list:
         if proc.name == 'aria2c':
             return proc.pid
     return None
Ejemplo n.º 44
0
def findProcess(name):
    procs = psutil.get_process_list()
    for proc in procs:
        try:
            if name in proc.name():
                return proc.pid
        except psutil.AccessDenied:
            continue
    return -1
Ejemplo n.º 45
0
def getJarnacProcess():
    procs = psutil.get_process_list()
    for p in procs:
        try:
            if p.name().find('Jarnac') >= 0:
                return p
        except psutil.AccessDenied:
            pass
    raise Exception("Jarnac does not appear to be running")
Ejemplo n.º 46
0
Archivo: monitor.py Proyecto: 4l1fe/spp
def findProcess(name):
    procs = psutil.get_process_list()
    for proc in procs:
        try:
            if name in proc.name():
                return proc.pid
        except psutil.AccessDenied:
            continue
    return -1
Ejemplo n.º 47
0
def process_pid(pname):
    pid = None
    processinfo = psutil.get_process_list()
    for one in processinfo:
        one_str = str(one)
        patt = re.compile(pname, re.I)
        if patt.search(one_str):
            pid = int(one_str.split('pid=')[1].split(',')[0])
    return pid
Ejemplo n.º 48
0
 def _sys_process_info(self, services):
     res = psutil.get_process_list()
     for x in services:
         container = []
         for i in res:
             if i.name() == x:
                 container.append(i.pid)
         self._sys_process_set[x] = str(container)
     return self._sys_process_set
Ejemplo n.º 49
0
def get_process_list(*args, **kwargs):
    processList = []
    for process in psutil.get_process_list(*args, **kwargs):
        #intercept the object and rewrap it in a nicer implementation.
        try:
            processList.append(IPsutilProcess(process))
        except:
            continue
    return processList
Ejemplo n.º 50
0
    def process(self, data, historys):
        '''插件方法,必须实现
        data是最新的计数数据,caches是最近的数据'''
        process_list = psutil.get_process_list()
        for rule in self.rules:
            if not self._isrun(process_list, rule.patt):
                return self._get_send_data(rule)

        return None
def pid_matched(pid, path):
    #Check the PID exists and the PATH match
    exe_path = ""
    procs = psutil.get_process_list()
    for proc in procs:
        if proc.pid == pid:
            exe_path = str(proc.exe)
            break
    return exe_path.lower() == path.lower()    
Ejemplo n.º 52
0
def process_pid(pname):
    pid = None
    processinfo = psutil.get_process_list()
    for one in processinfo:
        one_str = str(one)
        patt = re.compile(pname, re.I)
        if patt.search(one_str):
            pid = int(one_str.split('pid=')[1].split(',')[0])
    return pid
Ejemplo n.º 53
0
    def get_ui(self):
        ui = self.app.inflate('taskmgr:main')
        l = psutil.get_process_list()
        l = sorted(l, key=self.sort_key)
        if self._sort[1]:
            l = reversed(l)

        for x in l:
            try:
                ui.append(
                    'list',
                    UI.DTR(
                        UI.Image(file='/dl/core/ui/stock/service-%s.png' %
                                 ('run' if x.is_running() else 'stop')),
                        UI.Label(text=str(x.pid)),
                        UI.Label(text=str(int(x.get_cpu_percent()))),
                        UI.Label(text=str(int(x.get_memory_percent()))),
                        UI.Label(text=pwd.getpwuid(x.uid)[0]),
                        UI.Label(text=x.name),
                        UI.TipIcon(icon='/dl/core/ui/stock/info.png',
                                   id='info/%i' % x.pid,
                                   text='Info')))
            except:
                pass

        hdr = ui.find('sort/' + self._sort[0])
        hdr.set('text', ('↑ ' if self._sort[1] else '↓ ') + hdr['text'])

        if self._info is not None:
            try:
                p = filter(lambda x: x.pid == self._info, l)[0]
                iui = self.app.inflate('taskmgr:info')
                iui.find('name').set('text', '%i / %s' % (p.pid, p.name))
                iui.find('cmd').set('text',
                                    ' '.join("'%s'" % x for x in p.cmdline))
                iui.find('uid').set(
                    'text', '%s (%s)' % (pwd.getpwuid(p.uid)[0], p.uid))
                iui.find('gid').set('text', str(p.gid))
                iui.find('times').set(
                    'text', ' / '.join(str(x) for x in p.get_cpu_times()))
                if p.parent:
                    iui.find('parent').set('text', p.parent.name)
                    iui.find('parentinfo').set('id', 'info/%i' % p.parent.pid)
                else:
                    iui.remove('parentRow')

                sigs = [(x, getattr(signal, x)) for x in dir(signal)
                        if x.startswith('SIG')]

                for x in sigs:
                    iui.append('sigs', UI.SelectOption(text=x[0], value=x[1]))
                ui.append('main', iui)
            except:
                pass

        return ui
Ejemplo n.º 54
0
def getOneProcessByKeyword(keyword):
    recpl = re.compile(keyword, re.I)
    processList = psutil.get_process_list()
    for process in processList:
        try:
            cmdlineStr = " ".join(process.cmdline())
        except:
            continue
        if recpl.search(cmdlineStr):
            return process
def get_top_info():
    processes = psutil.get_process_list()

    for p in processes:
        try:
            proc_annotate_with_short_info(p)
        except psutil.NoSuchProcess:
            processes.remove(p)

    return processes
Ejemplo n.º 56
0
Archivo: pid.py Proyecto: hucc/learn-py
def getpid(key):

    for i in psutil.get_process_list():
        # print len(i.cmdline()),i.cmdline()
        if len(i.cmdline()) > 0:

            for c in i.cmdline():
                if c.find(key) != -1:
                    print i.cmdline()
                    return i.pid
Ejemplo n.º 57
0
def get_proc_by_name(proc_name='firefox'):
	'''
	Returns the process object. 	
	'''
	proc = None;
	procs = psutil.get_process_list()
	for p in procs:
		if proc_name.upper() == p.name.upper():
			proc = p;
	return proc