def main(options): verbose = options["--verbose"] interval = float(options["--interval"]) propyte.start_messaging_Pushbullet() users_previous = set([suser.name for suser in psutil.users()]) number_of_users_previous = len([suser.name for suser in psutil.users()]) while True: users = set([suser.name for suser in psutil.users()]) number_of_users = len([suser.name for suser in psutil.users()]) if verbose: print("\n" + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S Z")) print("current unique users: " + str(list(users))) print("current number of users: " + str(number_of_users)) symmetric_difference = list(users.symmetric_difference(users_previous)) if symmetric_difference: text = "users change detected: " + ", ".join(symmetric_difference) print(text) propyte.send_message_Pushbullet(text = text) if number_of_users != number_of_users_previous: text = "number of users changed" print(text) propyte.send_message_Pushbullet(text = text) users_previous = users number_of_users_previous = number_of_users time.sleep(interval)
def test_users(self): out = sh("who") lines = out.split('\n') users = [x.split()[0] for x in lines] terminals = [x.split()[1] for x in lines] self.assertEqual(len(users), len(psutil.users())) for u in psutil.users(): self.assertIn(u.name, users) self.assertIn(u.terminal, terminals)
def test_users(self): out = sh("who") lines = out.split('\n') users = [x.split()[0] for x in lines] self.assertEqual(len(users), len(psutil.users())) terminals = [x.split()[1] for x in lines] for u in psutil.users(): self.assertTrue(u.name in users, u.name) self.assertTrue(u.terminal in terminals, u.terminal)
def get_osinfo(): os_info = {} os_info['os_type'] = platform.system() os_info['os_system'] = platform.linux_distribution()[0] os_info['os_version'] = platform.linux_distribution()[1] os_info['os_kernel'] = platform.release() os_info['os_hostname'] = platform.node() os_info['os_starttime'] = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") os_info['users_count'] = len(psutil.users()) os_info['users_list'] = ",".join([u.name for u in psutil.users()]) os_info['users_host'] = ",".join([u.host for u in psutil.users()]) return os_info
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
def get_state(self): users = psutil.users() if len(users) == 0: state = "SLEEP" else: state = "RUNNING" return state
def run_pids(self): self.nodes.clear_widgets() self.lista = [] var = subprocess.check_output(['ps','-u',psutil.users()[0].name]) # tercer parametro selecciona el usuario del sistema ren = var.split('\n') #obteniendo reglones cont = 0 #control ignora primera y ultima linea for n in ren: cont = cont + 1 if cont == 1: pass elif cont == len(ren): pass #ultima linea a ignorar else: process = n.split() if sys.platform.startswith("linux"): selected = 0 elif sys.platform.startswith("darwin"): #OSX selected = 1 else: print "NOT SUPPORTED" #EXCEPTION? self.lista.append(int(process[selected])) #Vamos a introducir cada uno de los PIDs que se puedan usar en la lista de scroll .:D for p in self.lista: self.nodes.add_widget(Button(text='[color=00ff00]PID: {0}[/color]'.format(p), markup= True, font_size = '15sp', height='200sp')) self.nodes.size = (200, 40000)
def get_users(): dict = {} #find current users and add to the the dictionary try: users = psutil.users() names = [] for user in users: names.append(user[0]) dict['current_users'] = names except: print "Current Users not found" #find all users try: all_users = [] for p in pwd.getpwall(): all_users.append(p[0]) dict['all_users'] = all_users except: print "All Users not found" #make a dict of the groups of all the users try: groups = {} for p in pwd.getpwall(): groups[p[0]] = grp.getgrgid(p[3])[0] dict['groups'] = groups except: print "Groups not found" return dict
def test_users(self): # Duplicate of test_system.py. Keep it anyway. for user in psutil.users(): self.assertIsInstance(user.name, str) self.assertIsInstance(user.terminal, (str, type(None))) self.assertIsInstance(user.host, (str, type(None))) self.assertIsInstance(user.pid, (int, type(None)))
def realTimeInfo(): rt_info = [] top_info = [] for p in psutil.process_iter(): try: p = p.as_dict(['pid', 'name', 'username', 'cpu_percent', 'memory_percent', 'create_time', 'status']) except psutil.NoSuchProcess: return json.dumps({'error':'NoSuchProcess'}) else: top_info.append([p.get('pid'), p.get('name'), p.get('username'), p.get('cpu_percent'), p.get('memory_percent'), datetime.datetime.fromtimestamp(p.get('create_time')).strftime("%Y-%m-%d %H:%M:%S"), p.get('status')]) nets = psutil.net_io_counters() #snetio(bytes_sent=42988, bytes_recv=42988, packets_sent=595, packets_recv=595, errin=0, errout=0, dropin=0, dropout=0) disks = psutil.disk_io_counters() #sdiskio(read_count=9837, write_count=43761, read_bytes=198268416, write_bytes=933855232, read_time=87870, write_time=35913990) mem = psutil.virtual_memory() #svmem(total=508686336L, available=432787456L, percent=14.9, used=480034816L, free=28651520L, active=214945792, inactive=228995072, buffers=43900928L, cached=360235008) rt_info.append(nets) rt_info.append(disks) rt_info.append(mem) rt_info.append(psutil.users()) rt_info.append(top_info) rt_info.append(get_cpu_temp()) rt_info.append(psutil.cpu_percent()) return json.dumps(rt_info)
def save_user_current(name = None): loginuser = os.path.join(Setdirectorytempinfo(), 'loginuser') if name is None: userlist = list(set([users[0] for users in psutil.users()])) if len(userlist) > 0: name = userlist[0] else: name = "system" if not os.path.exists(loginuser): result = { name : 1, 'suite' : [name], 'curent' : name} savejsonfile(loginuser,result) return result['curent'] datauseruser = loadjsonfile(loginuser) if name in datauseruser: datauseruser[name] = datauseruser[name] + 1 datauseruser['suite'].insert(0, name) else: datauseruser[name] = 1 datauseruser['suite'].insert(0, name) datauseruser['suite'] = datauseruser['suite'][0:15] element = set(datauseruser['suite']) max = 0 for t in element: valcount = datauseruser['suite'].count(t) if valcount > max : datauseruser['curent'] = t savejsonfile(loginuser, datauseruser) return datauseruser['curent']
def show_current_users(): users = psutil.users() for user in users: print("User name:", user.name) print("User terminal:", user.terminal) print("Logged from host:", user.host) print("Logged on since:", get_date_string(user.started))
def _use_time_info(self): self._use_time['count_user'] = str(len(psutil.users())) self._use_time['start_time'] = str( datetime.datetime.fromtimestamp( psutil.boot_time()).strftime( "%Y-%m-%d %H:%M:%S")) return self._use_time
def retrieveInformationUsage(): global _ResourceInformation while True: info = {} # get CPU usage cpulist = [] cpu_usages = psutil.cpu_times_percent(None, True) for cpu in cpu_usages: cpuinfo = [cpu.system, cpu.user, cpu.idle, cpu.iowait, cpu.irq, cpu.softirq] cpulist.append(cpuinfo) info["cpu"] = cpulist # get Network IO netiocount = psutil.net_io_counters() packetinfo = [netiocount.packets_sent, netiocount.packets_recv] info["net"] = packetinfo # get Memory usage vMem = psutil.virtual_memory() info["mem"] = [vMem.used, vMem.free, vMem.total] # get disk space disk = psutil.disk_usage("/") info["disk"] = [disk.used, disk.free, disk.total] # get registered user registered_users = [] grplist = grp.getgrall() for group in grplist: if group.gr_name == "developer": registered_users = group.gr_mem userinfo = {} if len(registered_users) > 0: for reg_user in registered_users: if not userinfo.has_key(reg_user): userinfo[reg_user] = [] else: import pwd for p in pwd.getpwall(): if p.pw_uid >= 1000: if not userinfo.has_key(p[0]): userinfo[p[0]] = [] connected_user = psutil.users() for con_user in connected_user: if userinfo.has_key(con_user.name): userinfo[con_user.name].append([con_user.host, con_user.terminal]) info["user"] = userinfo _ResourceInformation = info postVMInformation(_MachineInformation, "Usage", _ResourceInformation) time.sleep(SLEEP_USAGEINFO) pass
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 main(): users = psutil.users() for user in users: print_("%-15s %-15s %s (%s)" % ( user.name, user.terminal or '-', datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M"), user.host))
def get_user_info(): print "\033[31m%s用户信息%s\033[0m" %(fg*30,fg*30) user = psutil.users() boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") print "系统开机时间:%s" %(boot_time) print "用户名\t\t终端\t\t主机\t\t登陆时间" for i in range(0,len(user)): login_time = datetime.datetime.fromtimestamp(user[i][3]).strftime("%Y-%m-%d %H:%M:%S") print "%s\t\t%s\t\t%s\t%s" %(user[i][0],user[i][1],user[i][2],login_time)
def test_users(self): users = psutil.users() self.assertNotEqual(users, []) for user in users: assert user.name, user user.terminal user.host assert user.started > 0.0, user datetime.datetime.fromtimestamp(user.started)
def System_info(environ,start_response): message="" status = '200 OK' headers = [('Content-type', 'html; charset=utf-8')] start_response(status, headers) disk_part = psutil.disk_partitions(all) no_of_cpu_core = psutil.cpu_count() memory = psutil.virtual_memory() # print(disk_part) user_name = psutil.users() message += "<center>" message += "<h3 font color = 'red'>"+"Hi, "+user_name[0][0]+"</h3>" message += "<p><em>Some Status of your System are</em></p>" message += "<p font color = 'blue'>Number of CPU cores = "+str(no_of_cpu_core)+"<p>" message += "<table width = '75%' border=0>" # message += '<tr bgcolor="#6BC9FF">' message += "<th bgcolor='#6BC9FF'>System Memory</th>" # message += "<table width = '50%' border=0>" message += "<tr bgcolor ='#FBFF6B' >" message += "<td bgcolor='#D8DF1C'>Total Memory</td><td>"+str(memory.total)+"</td>" message += "<td bgcolor='#D8DF1C' >Available Memory</td><td>"+str(memory.available)+"</td>" message += "<td bgcolor='#D8DF1C' >Used Memory</td><td>"+str(memory.used)+"</td>" message += "<td bgcolor='#D8DF1C' >Percent Used</td><td>"+str(memory.percent)+"%</td></tr>" message += "</table>" message += "</center>" print("Hi, "+ user_name[0][0]) print("Number of CPU cores = ",no_of_cpu_core) print("Total Memory = "+str(memory.total)+"\t"+"Used Memory = "+str(memory.used)+"\t"+"Free Memory = "+str(memory.available)+"\t"+"Percentage used = "+str(memory.percent)) i=0 for count in disk_part : drive_name = disk_part[i][1] usage = psutil.disk_usage(drive_name) # message += "<table width = '50%' border=0>" message += "<center>" message += "<table width = '75%' border=0>" # message += '<tr bgcolor="#6BC9FF">' message += "<th bgcolor='#6BC9FF'>Disk Usage</th>" message += "<tr bgcolor ='#FFD59E' >" message += "<td bgcolor='#FFA937'>Drive Name</td><td>"+count.device+"</td>" message += "<td bgcolor='#FFA937' >File System Type</td><td>"+count.fstype+"</td>" message += "<td bgcolor='#FFA937' >Total Memory</td><td>"+str(usage.total)+"</td>" message += "<td bgcolor='#FFA937' >Available Memory</td><td>"+str(usage.free)+"</td>" message += "<td bgcolor='#FFA937' >Used Memory</td><td>"+str(usage.used)+"</td>" message += "<td bgcolor='#FFA937' >Percent Used</td><td>"+str(usage.percent)+"%</td></tr>" message += "</table>" message += "</center>" print("Drive: "+count.device+"\t"+"File System Type: "+count.fstype+"\t"+"Capacity = "+str(usage.total)+"\t"+"Used space = "+str(usage.used)+"\t"+"Free Space="+str(usage.free)+"\t"+"Used Percentage = "+str(usage.percent)) # print("\t",psutil.disk_usage(drive_name)) # print("total usage="+str(usage.total)) i += 1 return[bytes(message,'utf-8')]
def test_users_mocked(self): # Make sure ':0' and ':0.0' (returned by C ext) are converted # to 'localhost'. with mock.patch('psutil._pslinux.cext.users', return_value=[('giampaolo', 'pts/2', ':0', 1436573184.0, True)]) as m: self.assertEqual(psutil.users()[0].host, 'localhost') assert m.called with mock.patch('psutil._pslinux.cext.users', return_value=[('giampaolo', 'pts/2', ':0.0', 1436573184.0, True)]) as m: self.assertEqual(psutil.users()[0].host, 'localhost') assert m.called # ...otherwise it should be returned as-is with mock.patch('psutil._pslinux.cext.users', return_value=[('giampaolo', 'pts/2', 'foo', 1436573184.0, True)]) as m: self.assertEqual(psutil.users()[0].host, 'foo') assert m.called
def poll_user(interval, stat): """ Fetch a list of users which are currently connected to the host :return: a list of unique users """ users = psutil.users() unique_users = set() for u in users: unique_users.add(u.name + "@" + u.host) stat['users'] = unique_users
def getUsers(self): arr = [] us = psutil.users() for u in us: if u[0] in arr: pass else: arr.append(u[0]) print arr return arr
def get_system_info(self,*args): load = os.getloadavg() virtmem = psutil.virtual_memory().percent swapmem = psutil.swap_memory().percent disk_usage = psutil.disk_usage('/').percent num_procs = len(psutil.pids()) user_count = len(set([ i.name for i in psutil.users()])) return [load,virtmem,swapmem, disk_usage,num_procs,user_count ]
def main(): users = psutil.users() for user in users: proc_name = psutil.Process(user.pid).name() if user.pid else "" print("%-12s %-10s %-10s %-14s %s" % ( user.name, user.terminal or '-', datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M"), "(%s)" % user.host if user.host else "", proc_name ))
def users(): print('-----------') print('LOGINED USERS\n-----------') users = psutil.users() for user in users: print("%-12s %-7s %s (%s)" % ( user.name, user.terminal or '-', datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M"), user.host)) print('-----------')
def misc(host, port, prefix, fields, debug=False): boot_time = psutil.boot_time() uptime = time.time() - boot_time client = statsd.StatsClient(host, port, prefix=prefix) with client.pipeline() as pipe: pipe.gauge('uptime{}'.format(fields), uptime) if debug: log.debug("uptime={}".format(uptime)) pipe.gauge('users{}'.format(fields), len(psutil.users())) pipe.gauge('processes{}'.format(fields), len(psutil.pids()))
def commandUsers(message): chat_id = message["chat"]["id"] if not storage.isRegisteredUser(chat_id): sendAuthMessage(chat_id) return text = "" for user in psutil.users(): text = text + "{0}@{1} {2}\n".format(user.name, user.host, str(datetime.datetime.fromtimestamp(user.started))) sendTextMessage(chat_id, text)
def w(): # TODO user idle time not yet achieve user_idle_time = '0.00s' ret = [] for u in psutil.users(): ret.append([u.name, u.host, datetime.fromtimestamp(u.started).strftime("%H:%M"), user_idle_time ]) return ret
def get_users(): us = [{ 'name': u.name, 'term': u.terminal, 'host': u.host, 'started': datetime.fromtimestamp(u.started) } for u in psutil.users()] return jsonify({ 'users': us })
class TestScripts(unittest.TestCase): """Tests for scripts in the "scripts" directory.""" @staticmethod def assert_stdout(exe, args=None, **kwds): exe = '"%s"' % os.path.join(SCRIPTS_DIR, exe) if args: exe = exe + ' ' + args try: out = sh(sys.executable + ' ' + exe, **kwds).strip() except RuntimeError as err: if 'AccessDenied' in str(err): return str(err) else: raise assert out, out return out @staticmethod def assert_syntax(exe, args=None): exe = os.path.join(SCRIPTS_DIR, exe) if PY3: f = open(exe, 'rt', encoding='utf8') else: f = open(exe, 'rt') with f: src = f.read() ast.parse(src) def test_coverage(self): # make sure all example scripts have a test method defined meths = dir(self) for name in os.listdir(SCRIPTS_DIR): if name.endswith('.py'): if 'test_' + os.path.splitext(name)[0] not in meths: # self.assert_stdout(name) self.fail('no test defined for %r script' % os.path.join(SCRIPTS_DIR, name)) @unittest.skipIf(not POSIX, "POSIX only") def test_executable(self): for name in os.listdir(SCRIPTS_DIR): if name.endswith('.py'): path = os.path.join(SCRIPTS_DIR, name) if not stat.S_IXUSR & os.stat(path)[stat.ST_MODE]: self.fail('%r is not executable' % path) def test_disk_usage(self): self.assert_stdout('disk_usage.py') def test_free(self): self.assert_stdout('free.py') def test_meminfo(self): self.assert_stdout('meminfo.py') def test_procinfo(self): self.assert_stdout('procinfo.py', args=str(os.getpid())) # can't find users on APPVEYOR or TRAVIS @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(), "unreliable on APPVEYOR or TRAVIS") def test_who(self): self.assert_stdout('who.py') def test_ps(self): self.assert_stdout('ps.py') def test_pstree(self): self.assert_stdout('pstree.py') def test_netstat(self): self.assert_stdout('netstat.py') # permission denied on travis @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") def test_ifconfig(self): self.assert_stdout('ifconfig.py') @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported") def test_pmap(self): self.assert_stdout('pmap.py', args=str(os.getpid())) @unittest.skipIf(not HAS_MEMORY_FULL_INFO, "not supported") def test_procsmem(self): self.assert_stdout('procsmem.py', stderr=DEVNULL) def test_killall(self): self.assert_syntax('killall.py') def test_nettop(self): self.assert_syntax('nettop.py') def test_top(self): self.assert_syntax('top.py') def test_iotop(self): self.assert_syntax('iotop.py') def test_pidof(self): output = self.assert_stdout('pidof.py', args=psutil.Process().name()) self.assertIn(str(os.getpid()), output) @unittest.skipIf(not WINDOWS, "WINDOWS only") def test_winservices(self): self.assert_stdout('winservices.py') def test_cpu_distribution(self): self.assert_syntax('cpu_distribution.py') @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported") @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") def test_temperatures(self): self.assert_stdout('temperatures.py') @unittest.skipIf(not HAS_SENSORS_FANS, "not supported") @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") def test_fans(self): self.assert_stdout('fans.py') @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported") @unittest.skipIf(not HAS_BATTERY, "no battery") def test_battery(self): self.assert_stdout('battery.py') def test_sensors(self): self.assert_stdout('sensors.py')
if (print_type == 1) or isset(sys.argv, "cpu"): print_str += " CPU状态如下:\n" cpu_status = psutil.cpu_times() print_str = print_str + " user = "******"\n" print_str = print_str + " nice = " + str(cpu_status.nice) + "\n" print_str = print_str + " system = " + str(cpu_status.system) + "\n" print_str = print_str + " idle = " + str(cpu_status.idle) + "\n" print_str = print_str + " iowait = " + str(cpu_status.iowait) + "\n" print_str = print_str + " irq = " + str(cpu_status.irq) + "\n" print_str = print_str + " softirq = " + str(cpu_status.softirq) + "\n" print_str = print_str + " steal = " + str(cpu_status.steal) + "\n" print_str = print_str + " guest = " + str(cpu_status.guest) + "\n" # 查看硬盘基本信息 if (print_type == 1) or isset(sys.argv, "disk"): print_str += " 硬盘信息如下:\n" disk_status = psutil.disk_partitions() for item in disk_status: print_str = print_str + " " + str(item) + "\n" # 查看当前登录的用户信息 if (print_type == 1) or isset(sys.argv, "user"): print_str += " 登录用户信息如下:\n " user_status = psutil.users() for item in user_status: print_str = print_str + " " + str(item) + "\n" print_str += "---------------------------------------------------------------\n" print(print_str) handle.write(print_str) handle.close()
def current_users(): # 返回当前用户总数 global user_counts user_counts = len(psutil.users()) return user_counts
def user_name(): # 返回当前用户名 global current_user current_user = psutil.users()[0].name return current_user
class TestMiscAPIs(unittest.TestCase): def test_boot_time(self): bt = psutil.boot_time() self.assertIsInstance(bt, float) self.assertGreater(bt, 0) self.assertLess(bt, time.time()) @unittest.skipIf(CI_TESTING and not psutil.users(), "unreliable on CI") def test_users(self): users = psutil.users() self.assertNotEqual(users, []) for user in users: assert user.name, user self.assertIsInstance(user.name, str) self.assertIsInstance(user.terminal, (str, type(None))) if user.host is not None: self.assertIsInstance(user.host, (str, type(None))) user.terminal user.host assert user.started > 0.0, user datetime.datetime.fromtimestamp(user.started) if WINDOWS or OPENBSD: self.assertIsNone(user.pid) else: psutil.Process(user.pid) @unittest.skipIf(not POSIX, 'POSIX only') def test_PAGESIZE(self): # pagesize is used internally to perform different calculations # and it's determined by using SC_PAGE_SIZE; make sure # getpagesize() returns the same value. import resource self.assertEqual(os.sysconf("SC_PAGE_SIZE"), resource.getpagesize()) def test_test(self): # test for psutil.test() function stdout = sys.stdout sys.stdout = DEVNULL try: psutil.test() finally: sys.stdout = stdout def test_os_constants(self): names = [ "POSIX", "WINDOWS", "LINUX", "MACOS", "FREEBSD", "OPENBSD", "NETBSD", "BSD", "SUNOS" ] for name in names: self.assertIsInstance(getattr(psutil, name), bool, msg=name) if os.name == 'posix': assert psutil.POSIX assert not psutil.WINDOWS names.remove("POSIX") if "linux" in sys.platform.lower(): assert psutil.LINUX names.remove("LINUX") elif "bsd" in sys.platform.lower(): assert psutil.BSD self.assertEqual( [psutil.FREEBSD, psutil.OPENBSD, psutil.NETBSD].count(True), 1) names.remove("BSD") names.remove("FREEBSD") names.remove("OPENBSD") names.remove("NETBSD") elif "sunos" in sys.platform.lower() or \ "solaris" in sys.platform.lower(): assert psutil.SUNOS names.remove("SUNOS") elif "darwin" in sys.platform.lower(): assert psutil.MACOS names.remove("MACOS") else: assert psutil.WINDOWS assert not psutil.POSIX names.remove("WINDOWS") # assert all other constants are set to False for name in names: self.assertIs(getattr(psutil, name), False, msg=name)
class TestSystemAPIs(unittest.TestCase): """Test some system APIs.""" @retry_on_failure() def test_pids(self): # Note: this test might fail if the OS is starting/killing # other processes in the meantime pids_ps = sorted(ps("pid")) pids_psutil = psutil.pids() # on MACOS and OPENBSD ps doesn't show pid 0 if MACOS or OPENBSD and 0 not in pids_ps: pids_ps.insert(0, 0) # There will often be one more process in pids_ps for ps itself if len(pids_ps) - len(pids_psutil) > 1: 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)) # for some reason ifconfig -a does not report all interfaces # returned by psutil @unittest.skipIf(SUNOS, "unreliable on SUNOS") @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") @unittest.skipIf(not which('ifconfig'), "no ifconfig cmd") @unittest.skipIf(not HAS_NET_IO_COUNTERS, "not supported") def test_nic_names(self): output = sh("ifconfig -a") for nic in psutil.net_io_counters(pernic=True).keys(): for line in output.split(): if line.startswith(nic): break else: self.fail("couldn't find %s nic in 'ifconfig -a' output\n%s" % (nic, output)) # can't find users on APPVEYOR or TRAVIS @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(), "unreliable on APPVEYOR or TRAVIS") @retry_on_failure() def test_users(self): out = sh("who") lines = out.split('\n') users = [x.split()[0] for x in lines] terminals = [x.split()[1] for x in lines] self.assertEqual(len(users), len(psutil.users())) for u in psutil.users(): self.assertIn(u.name, users) self.assertIn(u.terminal, terminals) def test_pid_exists_let_raise(self): # According to "man 2 kill" possible error values for kill # are (EINVAL, EPERM, ESRCH). Test that any other errno # results in an exception. with mock.patch("psutil._psposix.os.kill", side_effect=OSError(errno.EBADF, "")) as m: self.assertRaises(OSError, psutil._psposix.pid_exists, os.getpid()) assert m.called def test_os_waitpid_let_raise(self): # os.waitpid() is supposed to catch EINTR and ECHILD only. # Test that any other errno results in an exception. with mock.patch("psutil._psposix.os.waitpid", side_effect=OSError(errno.EBADF, "")) as m: self.assertRaises(OSError, psutil._psposix.wait_pid, os.getpid()) assert m.called def test_os_waitpid_eintr(self): # os.waitpid() is supposed to "retry" on EINTR. with mock.patch("psutil._psposix.os.waitpid", side_effect=OSError(errno.EINTR, "")) as m: self.assertRaises(psutil._psposix.TimeoutExpired, psutil._psposix.wait_pid, os.getpid(), timeout=0.01) assert m.called def test_os_waitpid_bad_ret_status(self): # Simulate os.waitpid() returning a bad status. with mock.patch("psutil._psposix.os.waitpid", return_value=(1, -1)) as m: self.assertRaises(ValueError, psutil._psposix.wait_pid, os.getpid()) assert m.called # AIX can return '-' in df output instead of numbers, e.g. for /proc @unittest.skipIf(AIX, "unreliable on AIX") def test_disk_usage(self): def df(device): out = sh("df -k %s" % device).strip() line = out.split('\n')[1] fields = line.split() total = int(fields[1]) * 1024 used = int(fields[2]) * 1024 free = int(fields[3]) * 1024 percent = float(fields[4].replace('%', '')) return (total, used, free, percent) tolerance = 4 * 1024 * 1024 # 4MB for part in psutil.disk_partitions(all=False): usage = psutil.disk_usage(part.mountpoint) try: total, used, free, percent = df(part.device) except RuntimeError as err: # see: # https://travis-ci.org/giampaolo/psutil/jobs/138338464 # https://travis-ci.org/giampaolo/psutil/jobs/138343361 err = str(err).lower() if "no such file or directory" in err or \ "raw devices not supported" in err or \ "permission denied" in err: continue else: raise else: self.assertAlmostEqual(usage.total, total, delta=tolerance) self.assertAlmostEqual(usage.used, used, delta=tolerance) self.assertAlmostEqual(usage.free, free, delta=tolerance) self.assertAlmostEqual(usage.percent, percent, delta=1)
def user_name(): arr = [] for user in psutil.users(): if str(user[0]) is not 'None' and user[0] not in arr: arr.append(user[0]) return arr
def apply(login): for user in login['add_users']: # make new user using vyatta shell and make home directory (-m), # default group of 100 (users) command = "useradd -m -N" # check if user already exists: if user['name'] in get_local_users(): # update existing account command = "usermod" # we need to use '' quotes when passing formatted data to the shell # else it will not work as some data parts are lost in translation command += " -p '{}'".format(user['password_encrypted']) command += " -s /bin/vbash" if user['full_name']: command += " -c '{}'".format(user['full_name']) if user['home_dir']: command += " -d '{}'".format(user['home_dir']) command += " -G frrvty,vyattacfg,sudo,adm,dip,disk" command += " {}".format(user['name']) try: cmd(command) uid = getpwnam(user['name']).pw_uid gid = getpwnam(user['name']).pw_gid # we should not rely on the home dir value stored in user['home_dir'] # as if a crazy user will choose username root or any other system # user this will fail. should be deny using root at all? home_dir = getpwnam(user['name']).pw_dir # install ssh keys ssh_key_dir = home_dir + '/.ssh' if not os.path.isdir(ssh_key_dir): os.mkdir(ssh_key_dir) os.chown(ssh_key_dir, uid, gid) os.chmod(ssh_key_dir, S_IRWXU | S_IRGRP | S_IXGRP) ssh_key_file = ssh_key_dir + '/authorized_keys' with open(ssh_key_file, 'w') as f: f.write("# Automatically generated by VyOS\n") f.write("# Do not edit, all changes will be lost\n") for id in user['public_keys']: line = '' if id['options']: line = '{} '.format(id['options']) line += '{} {} {}\n'.format(id['type'], id['key'], id['name']) f.write(line) os.chown(ssh_key_file, uid, gid) os.chmod(ssh_key_file, S_IRUSR | S_IWUSR) except Exception as e: raise ConfigError( 'Adding user "{}" raised an exception: {}'.format( user['name'], e)) for user in login['del_users']: try: # Logout user if he is logged in if user in list(set([tmp[0] for tmp in users()])): print('{} is logged in, forcing logout'.format(user)) call('pkill -HUP -u {}'.format(user)) # Remove user account but leave home directory to be safe call(f'userdel -r {user}', stderr=DEVNULL) except Exception as e: raise ConfigError( 'Deleting user "{}" raised an exception: {}'.format(user, e)) # # RADIUS configuration # if len(login['radius_server']) > 0: try: env = os.environ.copy() env['DEBIAN_FRONTEND'] = 'noninteractive' # Enable RADIUS in PAM cmd("pam-auth-update --package --enable radius", env=env) # Make NSS system aware of RADIUS, too command = "sed -i -e \'/\smapname/b\' \ -e \'/^passwd:/s/\s\s*/&mapuid /\' \ -e \'/^passwd:.*#/s/#.*/mapname &/\' \ -e \'/^passwd:[^#]*$/s/$/ mapname &/\' \ -e \'/^group:.*#/s/#.*/ mapname &/\' \ -e \'/^group:[^#]*$/s/: */&mapname /\' \ /etc/nsswitch.conf" cmd(command) except Exception as e: raise ConfigError('RADIUS configuration failed: {}'.format(e)) else: try: env = os.environ.copy() env['DEBIAN_FRONTEND'] = 'noninteractive' # Disable RADIUS in PAM cmd("pam-auth-update --package --remove radius", env=env) command = "sed -i -e \'/^passwd:.*mapuid[ \t]/s/mapuid[ \t]//\' \ -e \'/^passwd:.*[ \t]mapname/s/[ \t]mapname//\' \ -e \'/^group:.*[ \t]mapname/s/[ \t]mapname//\' \ -e \'s/[ \t]*$//\' \ /etc/nsswitch.conf" cmd(command) except Exception as e: raise ConfigError( 'Removing RADIUS configuration failed.\n{}'.format(e)) return None
def users_data(request): return Response({"users": psutil.users()}, status=status.HTTP_200_OK)
class TestSystemAPIs(unittest.TestCase): """Test some system APIs.""" @retry_before_failing() def test_pids(self): # Note: this test might fail if the OS is starting/killing # other processes in the meantime if SUNOS: 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 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)) # for some reason ifconfig -a does not report all interfaces # returned by psutil @unittest.skipIf(SUNOS, "unreliable on SUNOS") @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") def test_nic_names(self): p = subprocess.Popen("ifconfig -a", shell=1, stdout=subprocess.PIPE) output = p.communicate()[0].strip() if p.returncode != 0: raise unittest.SkipTest('ifconfig returned no output') if PY3: output = str(output, sys.stdout.encoding) for nic in psutil.net_io_counters(pernic=True).keys(): for line in output.split(): if line.startswith(nic): break else: self.fail("couldn't find %s nic in 'ifconfig -a' output\n%s" % (nic, output)) # can't find users on APPVEYOR or TRAVIS @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(), "unreliable on APPVEYOR or TRAVIS") @retry_before_failing() def test_users(self): out = sh("who") lines = out.split('\n') users = [x.split()[0] for x in lines] self.assertEqual(len(users), len(psutil.users())) terminals = [x.split()[1] for x in lines] for u in psutil.users(): self.assertTrue(u.name in users, u.name) self.assertTrue(u.terminal in terminals, u.terminal) def test_pid_exists_let_raise(self): # According to "man 2 kill" possible error values for kill # are (EINVAL, EPERM, ESRCH). Test that any other errno # results in an exception. with mock.patch("psutil._psposix.os.kill", side_effect=OSError(errno.EBADF, "")) as m: self.assertRaises(OSError, psutil._psposix.pid_exists, os.getpid()) assert m.called def test_os_waitpid_let_raise(self): # os.waitpid() is supposed to catch EINTR and ECHILD only. # Test that any other errno results in an exception. with mock.patch("psutil._psposix.os.waitpid", side_effect=OSError(errno.EBADF, "")) as m: self.assertRaises(OSError, psutil._psposix.wait_pid, os.getpid()) assert m.called def test_os_waitpid_eintr(self): # os.waitpid() is supposed to "retry" on EINTR. with mock.patch("psutil._psposix.os.waitpid", side_effect=OSError(errno.EINTR, "")) as m: self.assertRaises(psutil._psposix.TimeoutExpired, psutil._psposix.wait_pid, os.getpid(), timeout=0.01) assert m.called def test_os_waitpid_bad_ret_status(self): # Simulate os.waitpid() returning a bad status. with mock.patch("psutil._psposix.os.waitpid", return_value=(1, -1)) as m: self.assertRaises(ValueError, psutil._psposix.wait_pid, os.getpid()) assert m.called def test_disk_usage(self): def df(device): out = sh("df -k %s" % device).strip() line = out.split('\n')[1] fields = line.split() total = int(fields[1]) * 1024 used = int(fields[2]) * 1024 free = int(fields[3]) * 1024 percent = float(fields[4].replace('%', '')) return (total, used, free, percent) tolerance = 4 * 1024 * 1024 # 4MB for part in psutil.disk_partitions(all=False): usage = psutil.disk_usage(part.mountpoint) try: total, used, free, percent = df(part.device) except RuntimeError as err: # see: # https://travis-ci.org/giampaolo/psutil/jobs/138338464 # https://travis-ci.org/giampaolo/psutil/jobs/138343361 if "no such file or directory" in str(err).lower() or \ "raw devices not supported" in str(err).lower(): continue else: raise else: self.assertAlmostEqual(usage.total, total, delta=tolerance) self.assertAlmostEqual(usage.used, used, delta=tolerance) self.assertAlmostEqual(usage.free, free, delta=tolerance) self.assertAlmostEqual(usage.percent, percent, delta=1)
print 'virtual memory' print o u = psutil.swap_memory() print 'swap memory' print u y = psutil.disk_partitions() print 'disk partitions' print y q = psutil.disk_usage('/') print 'disk usage' print q w = psutil.net_io_counters(pernic=True) print 'interface io' print w #psutil.net_connections() x = psutil.net_if_addrs() print '#############################################' print 'interface addresses' print '#############################################' print x psutil.net_if_stats() psutil.users()
def __init__(self, cpu=None, users=None, mem=None, listen=None, remote=None, idle=None): if cpu is None: try: self.cpu = int(psutil.cpu_percent()) except: self.cpu = 0 else: self.cpu = int(cpu) if users is None: try: self.users = len(set([x.name for x in psutil.users()])) except: self.users = 0 else: self.users = int(users) if self.users > 255: self.users = 255 if mem is None: try: self.mem = int(psutil.virtual_memory().percent) except: self.mem = 0 else: self.mem = int(mem) if listen is None: try: self.listen = len( set([ x.laddr[1] for x in psutil.net_connections() if x.status == 'LISTEN' ])) except: self.listen = 0 else: self.listen = int(listen) if self.listen > 255: self.listen = 255 if remote is None: try: self.remote = len(set([ x.raddr for x in psutil.net_connections() \ if x.status=='ESTABLISHED' and x.raddr[0] not in ( '127.0.0.1', '::ffff:127.0.0.1' ) ])) except: self.remote = 0 else: self.remote = int(remote) if self.remote > 255: self.remote = 255 if idle is None: if uidle is None: self.idle = True else: try: idle = uidle.get_idle() if idle is None: self.idle = True else: self.idle = idle > 60 * 10 except: self.idle = True else: self.idle = bool(idle)
psutil.disk_usage() ### 磁盘IO信息[read_count读IO数、write_count写IO数、IO读字节数read_bytes、 ### IO写字节数write_bytes、磁盘读时间read_time、磁盘写时间write_time] psutil.disk_partitions() # 获取磁盘完整信息 psutil.disk_io_counters() # 获取硬盘总的IO个数、读写信息 psutil.disk_io_counters(perdisk=True) # 获取单个硬盘的IO个数、读写信息 ## 网络信息 ### bytes_sent 发送字节数 ### bytes_recv 接收字节数 ### packet_sent 发送数据包数 psutil.net_io_counters() # 获取网络总的IO信息 psutil.net_io_counters(pernic=True) # 获取每个网络接口的IO信息 ## 其他系统信息 psutil.users() # 返回当前登录系统的用户信息 psutil.boot_time() # 开始时间 datetime.datetime.fromtimestamp( psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") # 系统进程管理 ## 进程信息 psutil.pids() # 列出所有进程的PID p = psutil.Process(psutil.pids()[0]) # 实例化一个Process对象,参数为一进程PID p.name() # 进程名 p.exe() # 进程的bin路径 p.cwd() # 进程的工作目录的绝对路径 p.status() # 进程状态 p.create_time() # 进程创建时间,时间戳格式 p.uids() # 进程uid信息 p.gids() # 进程gid信息
def get_users_list(): """Return list of active users count""" users = len(psutil.users()) print(users) return users
def user_details(): return psutil.users()
def OTHER(self): login_users=len(psutil.users()) pid_nums=len(psutil.pids()) return json.dumps({"LoginUserNums": int(login_users), "PidNums": int(pid_nums)})
def get_users(self): return [u._asdict() for u in psutil.users()]
# DISK information try: disk = psutil.disk_usage('/') except: disk = "\033[1mNO DATA RECEIVED\033[0m" # BATTERY information try: battery = psutil.sensors_battery() except: battery = "\033[1mNO DATA RECEIVED\033[0m" # USERS logged in user try: users = psutil.users() except: users = "\033[1mNO DATA RECEIVED\033[0m" # USERS ammount of logged in users try: userammount = os.popen('who | wc -l').read() userammount = userammount.rstrip() except: userammount = "\033[1mNO DATA RECEIVED\033[0m" ################################################################################ # C L E A R S C R E E N # ################################################################################ clear()
def username(): username = psutil.users() for user_name in username: first_name = user_name[0] speak(f"Sir, this computer is signed to {first_name} as a username.")
print("-----------cpu_count-----------") print(psutil.cpu_count()) # 返回系统中逻辑cpu的数量 print("-----------cpu_freq-----------") print(psutil.cpu_freq()) # 返回CPU频率 print("-----------cpu_percent-----------") print(psutil.cpu_percent()) # 返回当前系统CPU利用率(float类型) print("-----------cpu_stats-----------") print(psutil.cpu_stats()) # 返回CPU统计数据 print("-----------cpu_times-----------") print(psutil.cpu_times()) # 返回系统范围内的CPU时间。 print("-----------cpu_times_percent-----------") print(psutil.cpu_times_percent()) # 对于每个特定的CPU时间提供利用率,由cpu_times()返回。 print("-----------boot_time-----------") print(psutil.boot_time()) # 返回从1970以来以秒表示的系统启动时间 print("-----------users-----------") print(psutil.users()) # 返回当前连接在系统上的用户列表 print("-----------test-----------") print(psutil.test()) # 列出所有当前正在运行的进程信息 """ 结果 -----------cpu_count----------- 4 -----------cpu_freq----------- scpufreq(current=3168.0, min=0.0, max=3201.0) -----------cpu_percent----------- 0.0 -----------cpu_stats----------- scpustats(ctx_switches=861048211, interrupts=148032987, soft_interrupts=0, syscalls=1186688671) -----------cpu_times----------- scputimes(user=6015.96044921875, system=2641.171875, idle=79255.78125, interrupt=93.52259969711304, dpc=523.3521823883057)
import psutil print(psutil.users()[0].name)
def update_users(self): self.clear() for u in psutil.users(): self.add(u.name)
def getLoggedUsersCount(self): """Getter for amount of logged users""" return len(psutil.users())
def get_active_users(): users = psutil.users() users2 =[] for i in range(len(users)): users2.append(users[i].name) return users2
def gen_sys_info() -> (str, list): '''生成简单的系统状态文本,会产生5秒延时 返回: 系统状态清单 警告信息 ''' def graph_process(percent: int, length: int = 15): '''生成进度条,percent为进度[0-100],length为长度''' percent_count = int(length * percent / 100) return ( f'{str(percent).rjust(4)}% [{"#"*percent_count}{"_"*(length-percent_count)}]' ) def check_status(): '''判断数值是否异常''' warns = [] if cpu_percent >= 95: warns.append(' CPU负载过高\n') if mem_percent >= 95: warns.append(' 内存占用过高\n') for load in cpu_load: if load + 0.3 >= cpu_trade: warns.append(' 系统负载过高\n') break for usage in disk_percent: if usage >= 95: warns.append(' 磁盘空间不足\n') break if warns: return (f'警告信息:\n{"".join(warns)}\n') else: return (False) uname = platform.uname() sys_hostname = uname.node sys_type = uname.system if sys_type == 'Linux': sys_version = ' '.join(platform.dist()) else: sys_version = f'{uname.system} {uname.version}' time_boot = datetime.fromtimestamp(psutil.boot_time()) time_curr = datetime.now() time_pass = time_curr - time_boot cpu_percent = psutil.cpu_percent() cpu_core = psutil.cpu_count(logical=False) cpu_trade = psutil.cpu_count(logical=True) cpu_load = psutil.getloadavg() mem = psutil.virtual_memory() mem_total = mem.total mem_used = mem.used mem_percent = mem.percent disk_info = [] disk_percent = [] for d in psutil.disk_partitions(): if d.fstype: usage = psutil.disk_usage(d.mountpoint) d_total = usage.total d_used = usage.used d_percent = usage.percent disk_percent.append(d_percent) disk_info.append(f'磁盘{d.mountpoint.ljust(9)}: ' f'{graph_process(d_percent)} ' f'{size2str(d_used)}/{size2str(d_total)}\n') else: d_total = 0 d_used = 0 d_percent = 0 disk_info.append( f'磁盘{d.mountpoint.ljust(9)}: {graph_process(0)} 不可用\n') net_old = psutil.net_io_counters() sleep(5) net = psutil.net_io_counters() net_send_s = (net.bytes_sent - net_old.bytes_sent) // 5 net_recv_s = (net.bytes_recv - net_old.bytes_recv) // 5 net_send = net.bytes_sent net_recv = net.bytes_recv user_info = [] for i, user in enumerate(psutil.users(), 1): u_name = user.name u_host = user.host u_start = user.started user_info.append(f' {i}. {u_name} [{u_host}] 自 ' f'{datetime2str(datetime.fromtimestamp(u_start))}\n') warns = check_status() msg = ( f'{"系统状态".center(50,"=")}\n' f'{warns if warns else ""}' f'主机名称{" "*6}:{sys_hostname}\n' f'系统版本{" "*6}:{sys_version}\n' '\n' f'当前时间{" "*6}:{datetime2str(time_curr)}\n' f'运行时间{" "*6}:{time_pass.days}天{int(time_pass.seconds//3600)}时\n' f'平均负载{" "*6}:{cpu_load[0]} {cpu_load[1]} {cpu_load[2]}\n' '\n' f'CPU使用{" "*6}:{graph_process(cpu_percent)} ' f'{cpu_core}C{cpu_trade}T\n' f'内存使用{" "*6}:{graph_process(mem_percent)} ' f'{size2str(mem_used)}/{size2str(mem_total)}\n' f'{"".join(disk_info)}\n' f'当前流量{" "*6}:{size2str(net_send_s)}/S 发送 {size2str(net_recv_s)}/S 接收\n' f'累计流量{" "*6}:{size2str(net_send)} 发送 {size2str(net_recv)} 接收\n' '\n' f'登陆用户{" "*6}:\n{"".join(user_info) if user_info else " 无登录用户"}') return (msg, warns)
mem = psutil.virtual_memory() print mem.total print mem.free print mem.used swap = psutil.swap_memory() print swap.total print swap.free print swap.used disk = psutil.disk_partitions() print disk disk_io = psutil.disk_io_counters(perdisk=True) print disk_io print disk_io.get('PhysicalDrive1') print disk_io.get('PhysicalDrive0') user = psutil.users() print user boot_time = psutil.boot_time() print datetime.datetime.fromtimestamp(boot_time).strftime("%H:%M:%S %Y/%m/%d") net_io = psutil.net_io_counters() print net_io.bytes_recv print net_io.bytes_sent print net_io[1] print net_io[0] print net_io
#free -m | grep Mem |awk '{print $2}' //total #free -m | grep Mem |awk '{print $4}' //free ###################内存############################# mem = psutil.virtual_memory() print('total:%s' % (mem.total)) print('used:%s' % (mem.used)) print('free:%s' % (mem.free)) print('available:%s' % (mem.available)) ####################cup########################### print(psutil.cpu_times().user) print(psutil.cpu_count()) print(psutil.cpu_count(logical=False)) ####################磁盘############################ disk = psutil.disk_partitions() print(disk) print(psutil.disk_usage('/')) #根分区信息 print(psutil.disk_io_counters(perdisk=True)) #####################网络########################### list = psutil.net_io_counters(pernic=True) print(list['enp1s0']) ######################登陆用户########################## print(psutil.users()) ######################进程############################# print(psutil.pids()) p = psutil.Process(20) print(p.name()) print(p.exe()) print(p.cwd())
class TestScripts(unittest.TestCase): """Tests for scripts in the "scripts" directory.""" def assert_stdout(self, exe, args=None): exe = '"%s"' % os.path.join(SCRIPTS_DIR, exe) if args: exe = exe + ' ' + args try: out = sh(sys.executable + ' ' + exe).strip() except RuntimeError as err: if 'AccessDenied' in str(err): return str(err) else: raise assert out, out return out def assert_syntax(self, exe, args=None): exe = os.path.join(SCRIPTS_DIR, exe) with open(exe, 'r') as f: src = f.read() ast.parse(src) def test_coverage(self): # make sure all example scripts have a test method defined meths = dir(self) for name in os.listdir(SCRIPTS_DIR): if name.endswith('.py'): if 'test_' + os.path.splitext(name)[0] not in meths: # self.assert_stdout(name) self.fail('no test defined for %r script' % os.path.join(SCRIPTS_DIR, name)) @unittest.skipUnless(POSIX, "POSIX only") def test_executable(self): for name in os.listdir(SCRIPTS_DIR): if name.endswith('.py'): path = os.path.join(SCRIPTS_DIR, name) if not stat.S_IXUSR & os.stat(path)[stat.ST_MODE]: self.fail('%r is not executable' % path) def test_disk_usage(self): self.assert_stdout('disk_usage.py') def test_free(self): self.assert_stdout('free.py') def test_meminfo(self): self.assert_stdout('meminfo.py') def test_procinfo(self): self.assert_stdout('procinfo.py', args=str(os.getpid())) # can't find users on APPVEYOR or TRAVIS @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(), "unreliable on APPVEYOR or TRAVIS") def test_who(self): self.assert_stdout('who.py') def test_ps(self): self.assert_stdout('ps.py') def test_pstree(self): self.assert_stdout('pstree.py') def test_netstat(self): self.assert_stdout('netstat.py') # permission denied on travis @unittest.skipIf(TRAVIS, "unreliable on TRAVIS") def test_ifconfig(self): self.assert_stdout('ifconfig.py') @unittest.skipIf(OPENBSD or NETBSD, "platform not supported") def test_pmap(self): self.assert_stdout('pmap.py', args=str(os.getpid())) @unittest.skipUnless(OSX or WINDOWS or LINUX, "platform not supported") def test_procsmem(self): self.assert_stdout('procsmem.py') def test_killall(self): self.assert_syntax('killall.py') def test_nettop(self): self.assert_syntax('nettop.py') def test_top(self): self.assert_syntax('top.py') def test_iotop(self): self.assert_syntax('iotop.py') def test_pidof(self): output = self.assert_stdout('pidof.py', args=psutil.Process().name()) self.assertIn(str(os.getpid()), output) @unittest.skipUnless(WINDOWS, "WINDOWS only") def test_winservices(self): self.assert_stdout('winservices.py') def test_cpu_distribution(self): self.assert_syntax('cpu_distribution.py') @unittest.skipIf(TRAVIS, "unreliable on travis") def test_temperatures(self): if hasattr(psutil, "sensors_temperatures"): self.assert_stdout('temperatures.py') else: self.assert_syntax('temperatures.py') def test_battery(self): if hasattr(psutil, "sensors_battery") and \ psutil.sensors_battery() is not None: self.assert_stdout('battery.py') else: self.assert_syntax('battery.py')
class TestScripts(PsutilTestCase): """Tests for scripts in the "scripts" directory.""" @staticmethod def assert_stdout(exe, *args, **kwargs): exe = '%s' % os.path.join(SCRIPTS_DIR, exe) cmd = [PYTHON_EXE, exe] for arg in args: cmd.append(arg) try: out = sh(cmd, **kwargs).strip() except RuntimeError as err: if 'AccessDenied' in str(err): return str(err) else: raise assert out, out return out @staticmethod def assert_syntax(exe, args=None): exe = os.path.join(SCRIPTS_DIR, exe) if PY3: f = open(exe, 'rt', encoding='utf8') else: f = open(exe, 'rt') with f: src = f.read() ast.parse(src) def test_coverage(self): # make sure all example scripts have a test method defined meths = dir(self) for name in os.listdir(SCRIPTS_DIR): if name.endswith('.py'): if 'test_' + os.path.splitext(name)[0] not in meths: # self.assert_stdout(name) raise self.fail('no test defined for %r script' % os.path.join(SCRIPTS_DIR, name)) @unittest.skipIf(not POSIX, "POSIX only") def test_executable(self): for root, dirs, files in os.walk(SCRIPTS_DIR): for file in files: if file.endswith('.py'): path = os.path.join(root, file) if not stat.S_IXUSR & os.stat(path)[stat.ST_MODE]: raise self.fail('%r is not executable' % path) def test_disk_usage(self): self.assert_stdout('disk_usage.py') def test_free(self): self.assert_stdout('free.py') def test_meminfo(self): self.assert_stdout('meminfo.py') def test_procinfo(self): self.assert_stdout('procinfo.py', str(os.getpid())) @unittest.skipIf(CI_TESTING and not psutil.users(), "no users") def test_who(self): self.assert_stdout('who.py') def test_ps(self): self.assert_stdout('ps.py') def test_pstree(self): self.assert_stdout('pstree.py') def test_netstat(self): self.assert_stdout('netstat.py') def test_ifconfig(self): self.assert_stdout('ifconfig.py') @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported") def test_pmap(self): self.assert_stdout('pmap.py', str(os.getpid())) def test_procsmem(self): if 'uss' not in psutil.Process().memory_full_info()._fields: raise self.skipTest("not supported") self.assert_stdout('procsmem.py') def test_killall(self): self.assert_syntax('killall.py') def test_nettop(self): self.assert_syntax('nettop.py') def test_top(self): self.assert_syntax('top.py') def test_iotop(self): self.assert_syntax('iotop.py') def test_pidof(self): output = self.assert_stdout('pidof.py', psutil.Process().name()) self.assertIn(str(os.getpid()), output) @unittest.skipIf(not WINDOWS, "WINDOWS only") def test_winservices(self): self.assert_stdout('winservices.py') def test_cpu_distribution(self): self.assert_syntax('cpu_distribution.py') @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported") def test_temperatures(self): if not psutil.sensors_temperatures(): self.skipTest("no temperatures") self.assert_stdout('temperatures.py') @unittest.skipIf(not HAS_SENSORS_FANS, "not supported") def test_fans(self): if not psutil.sensors_fans(): self.skipTest("no fans") self.assert_stdout('fans.py') @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported") @unittest.skipIf(not HAS_BATTERY, "no battery") def test_battery(self): self.assert_stdout('battery.py') @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported") @unittest.skipIf(not HAS_BATTERY, "no battery") def test_sensors(self): self.assert_stdout('sensors.py')
def get_user_node(): user_count = RunnableNode('count', method=lambda: (len([x.name for x in ps.users()]), 'users')) user_list = RunnableNode('list', method=lambda: ([x.name for x in ps.users()], 'users')) return ParentNode('user', children=[user_count, user_list])