def test_get_users(self): out = sh("who") lines = out.split('\n') users = [x.split()[0] for x in lines] self.assertEqual(len(users), len(psutil.get_users())) terminals = [x.split()[1] for x in lines] for u in psutil.get_users(): self.assertTrue(u.name in users, u.name) self.assertTrue(u.terminal in terminals, u.terminal)
def test_get_users(self): out = sh("who") lines = out.split("\n") users = [x.split()[0] for x in lines] self.assertEqual(len(users), len(psutil.get_users())) terminals = [x.split()[1] for x in lines] for u in psutil.get_users(): self.assertTrue(u.name in users, u.name) self.assertTrue(u.terminal in terminals, u.terminal)
def get_env_info(): '''Gets general information about the computer.''' infodict = OrderedDict() infodict["Name"] = platform.node() infodict["System"] = platform.system() infodict["System alias"] = " ".join(platform.system_alias( platform.system(), platform.release(), platform.version())) infodict["Platform"] = platform.platform() if infodict["System"] == "Linux": # System-specific information infodict["Distribution"] = " ".join(platform.dist()) elif infodict["System"] == "Windows": infodict["OS"] = " ".join(platform.win32_ver()) elif infodict["System"] == "MacOS": verinfo = platform.mac_ver()[1] macver = " ".join(platform.mac_ver()) macver[1] = verinfo infodict["OS"] = " ".join(macver) infodict["Boot time"] = datetime.datetime.fromtimestamp( psutil.get_boot_time()).strftime("%c") infodict["Uptime"] = str(datetime.datetime.fromtimestamp( time.time() - psutil.get_boot_time()).strftime("%d:%H:%M:%S:%f")) for user in psutil.get_users(): infodict["User '" + user.name + "' terminal"] = user.terminal infodict["User '" + user.name + "' host"] = user.host infodict["User '" + user.name + "' started"] = str( datetime.datetime.fromtimestamp(user.started).strftime("%c")) return infodict
def get_users(): sqlArr=[]; usrArr=[]; outflname="/tmp/sql/connUsers_"+ time.strftime('%Y%m%d%H%M%S')+".sql"; try: if majorVer < 2: usrArr=psutil.get_users(); else: usrArr=psutil.users(); totUsers=len(usrArr); i=0; while i < totUsers: user='******'+str(i); uname=usrArr[i].name; hname=string.replace(usrArr[i].host,':',''); started=usrArr[i].started; connStartTime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(started)); currentTime=time.strftime('%Y'+'-'+'%m'+'-'+'%d'+' '+'%H'+':'+'%M'+':'+'%S'); #print "Epoch Time connection started is %s" %started; #print "Time connection started is %s" %connStartTime; sqlstmt ='insert into sm_connected_users (hostip, hostname, num_of_users, conn_user, conn_user_name, conn_host_name, time_conn_start, snaptime) values '; sqlstmt+=' (\''+str(hostIP)+'\',\''+str(hostname)+'\',\''+str(totUsers)+'\',\''+str(user)+'\',\''+str(uname)+'\',\''+str(hname)+'\',timestamp \''+str(connStartTime)+'\',timestamp \''+str(currentTime)+'\');'; sqlArr.append(sqlstmt); i=i+1; statfl = open (outflname,"w"); statfl.write(string.join(sqlArr,'\n')+'commit;'); statfl.close(); except: pass
def get_users(): ''' Return logged-in users. CLI Example: .. code-block:: bash salt '*' ps.get_users ''' try: recs = psutil.get_users() return [dict(x._asdict()) for x in recs] except AttributeError: # get_users is only present in psutil > v0.5.0 # try utmp try: import utmp result = [] while True: rec = utmp.utmpaccess.getutent() if rec is None: return result elif rec[0] == 7: started = rec[8] if isinstance(started, tuple): started = started[0] result.append({'name': rec[4], 'terminal': rec[2], 'started': started, 'host': rec[5]}) except ImportError: return False
def main(): users = psutil.get_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 run(options, din, dout): printer = make_printer(dout) for item in psutil.get_users(): printer(item._asdict()) return OK
def Main(): cgiEnv = lib_common.CgiEnv() grph = cgiEnv.GetGraph() # [suser(name='Remi', terminal=None, host='0.246.33.0', started=1411052436.0)] try: # Windows XP, Python 3. try: # Windows XP, Python 3.4. users_list = psutil.users() except AttributeError: # Linux and Python 2.5 # Windows 7, Python 3.2 : mais c'est la version de psutil qui compte. users_list = psutil.get_users() except AttributeError: # AttributeError: 'module' object has no attribute 'users' lib_common.ErrorMessageHtml("Function users() not available") for user in users_list: usrNam = lib_common.FormatUser( user.name ) userNode = lib_common.gUriGen.UserUri( usrNam ) grph.add( ( lib_common.nodeMachine, pc.property_user, userNode ) ) cgiEnv.OutCgiRdf()
def get_users(): ''' Return logged-in users. CLI Example: .. code-block:: bash salt '*' ps.get_users ''' try: recs = psutil.get_users() return [dict(x._asdict()) for x in recs] except AttributeError: # get_users is only present in psutil > v0.5.0 # try utmp try: import utmp # pylint: disable=import-error result = [] while True: rec = utmp.utmpaccess.getutent() if rec is None: return result elif rec[0] == 7: started = rec[8] if isinstance(started, tuple): started = started[0] result.append({'name': rec[4], 'terminal': rec[2], 'started': started, 'host': rec[5]}) except ImportError: return False
def main(): users = psutil.get_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 w(): # TODO user idle time not yet achieve user_idle_time = '0.00s' ret = [] for u in psutil.get_users(): ret.append([ u.name, u.host, datetime.fromtimestamp(u.started).strftime("%H:%M"), user_idle_time ]) return ret
def w(): # TODO user idle time not yet achieve user_idle_time = '0.00s' ret = [] for u in psutil.get_users(): ret.append([u.name, u.host, datetime.fromtimestamp(u.started).strftime("%H:%M"), user_idle_time ]) return ret
def _get_users(): retval = {} try: tmp = psutil.users() if hasattr(psutil, 'users') else psutil.get_users() for session in tmp: # Count logged in users retval[session.name] = retval.get(session.name, 0) + 1 except: pass return retval
def get_users(): users = [] for u in psutil.get_users(): dt = datetime.fromtimestamp(u.started) user = { "name": u.name.decode("utf-8"), "terminal": u.terminal, "started": dt.strftime("%Y-%m-%d %H:%M:%S"), "host": u.host.decode("utf-8") } users.append(user) return users
def sysstat_who(self, args): users = psutil.get_users() return_str = [] for user in users: return_str.append( "%-15s %-15s %s (%s)" % ( user.name, user.terminal or "-", self.utils.get_short_age(user.started), # datetime.datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M"), user.host, ) ) return return_str
def current_users(): ldict = {"step": inspect.stack()[0][3], "hostname": platform.node().split(".")[0]} l = logging.LoggerAdapter(fetch_lg(), ldict) # l.info("Gathering logged in users...") host_users = [] for item in psutil.get_users(): user = item[0] term = item[1] host = item[2] host_users.append({"user": user, "terminal": term, "from": host}) return host_users
def u_con(): u = psutil.get_users() os.system('clear') for j in range (0, len(u)): s_Array = u[j] c_min = s_Array[3] / 60 print('####################') print('User >> ', s_Array[0]) print('Terminal >> ', s_Array[1]) print('Host >> ', s_Array[2]) print('Online Time >> ', s_Array[3]) print('\n\n\n') exit = input("Press any KEY to leave.") os.system('clear')
def get_user(self): l =[] d = {} rr = None try: for user in psutil.get_users(): duser = user._asdict() td = datetime.now() - datetime.fromtimestamp(duser['started']) td = str(td) td = td[:-7] duser['started'] = td rr = json.dumps(duser) return rr except Exception as e: self.logger.error("Pulling logged in info %s" % e) return rr
def set_users(self): """Gather informations of logged in users and store values in a hash""" # psutil < 2.0.0 if 'get_users' in dir(psutil): users_set = psutil.get_users() # psutil >= 2.0.0 else: users_set = psutil.users() users = [] for user in users_set: time = datetime.datetime.fromtimestamp( int(user.started)).strftime('%Y-%m-%d %H:%M:%S') users.append({ 'name': user.name, 'from': user.host, 'time': time }) self.users = users
def server(): global cpu_times def calculate(t1, t2): t1_all = sum(t1) t1_busy = t1_all - t1.idle t2_all = sum(t2) t2_busy = t2_all - t2.idle # this usually indicates a float precision issue if t2_busy <= t1_busy: return 0.0 busy_delta = t2_busy - t1_busy all_delta = t2_all - t1_all busy_perc = (busy_delta / all_delta) * 100 return round(busy_perc, 1) ret = {} ret.update({ "mem_" + key: val for key, val in psutil.virtual_memory().__dict__.iteritems() }) ret.update({ "cpu_ptime_" + key: val for key, val in psutil.cpu_times_percent().__dict__.iteritems() }) if None not in cpu_times: ret['cpu_percent'] = calculate(*cpu_times) else: ret['cpu_percent'] = 0 ret.update({ "diskio_" + key: val for key, val in psutil.disk_io_counters().__dict__.iteritems() }) ret.update({ "disk_" + key: val for key, val in psutil.disk_usage('/').__dict__.iteritems() }) users = psutil.get_users() ret['user_count'] = len(users) ret['user_info'] = [(u.name, u.host) for u in users] return jsonify(**ret)
def render_system(self): uptime = datetime.now() - datetime.fromtimestamp(System.boot_time()) uptime = str(uptime).split('.')[0] users = set([user.name for user in psutil.get_users()]) package_managers = System.package_manager().names() view = SystemView() view.assign('python', System.python_version()) view.assign('distribution', System.distribution()) view.assign('package_managers', package_managers) view.assign('init', System.init_system()) view.assign('uptime', uptime) view.assign('user', System.user()) view.assign('users', users) view.assign('version', __version__) view.assign('rules_count', len(Rules.all())) view.assign('applications_count', len(Applications.all())) view.render()
def _get_sys_info(self): '''This will populate some basic system information ### INPUT OTHER THAN INTEGERS IS CURRENLTLY NOT SUPPORTED BY NEW RELIC ###''' try: #self.metric_data['Component/System Information/Kernel[string]'] = self.kernel #self.metric_data['Component/System Information/Arch[string]'] = self.arch #self.metric_data['Component/System Information/Boot Time[datetime]'] = self._get_boottime() self.metric_data[ 'Component/System Information/Process Count[process]'] = len( psutil.get_pid_list()) self.metric_data[ 'Component/System Information/Core Count[core]'] = psutil.NUM_CPUS self.metric_data[ 'Component/System Information/Active Sessions[session]'] = len( psutil.get_users()) except Exception, e: loging.exception(e) pass
def server(): global cpu_times def calculate(t1, t2): t1_all = sum(t1) t1_busy = t1_all - t1.idle t2_all = sum(t2) t2_busy = t2_all - t2.idle # this usually indicates a float precision issue if t2_busy <= t1_busy: return 0.0 busy_delta = t2_busy - t1_busy all_delta = t2_all - t1_all busy_perc = (busy_delta / all_delta) * 100 return round(busy_perc, 1) ret = {} ret.update({"mem_" + key: val for key, val in psutil.virtual_memory().__dict__.iteritems()}) ret.update({"cpu_ptime_" + key: val for key, val in psutil.cpu_times_percent().__dict__.iteritems()}) if None not in cpu_times: ret['cpu_percent'] = calculate(*cpu_times) else: ret['cpu_percent'] = 0 ret.update({"diskio_" + key: val for key, val in psutil.disk_io_counters().__dict__.iteritems()}) ret.update({"disk_" + key: val for key, val in psutil.disk_usage('/').__dict__.iteritems()}) users = psutil.get_users() ret['user_count'] = len(users) ret['user_info'] = [(u.name, u.host) for u in users] return jsonify(**ret)
def get_users(): return psutil.get_users()
def get_users(self): return len(psutil.get_users())
def constantUpdateActor(self,config): #set duration number Ndur=self.duration #get current CPU percent busy percentcpubusy = psutil.cpu_percent() percentmembusy=psutil.virtual_memory().percent self.ui.progressBarStatusMemory.setValue(round(percentmembusy)) Ncpus=len(psutil.cpu_percent(percpu=True)) self.ui.Ncpus=Ncpus totalcpustr='CPU Count: '+str(Ncpus) # print "Total CPU str: ",totalcpustr self.ui.labelCPUCount.setText(totalcpustr+' - CPU Utilization:') totalmem=int(round(float(psutil.virtual_memory().total)/(1024*1024*1024))) #psutil syntax OK for both versions # print "Total Mem: ",totalmem self.ui.totalmem=totalmem totalmemstr=str(totalmem)+' GB' self.ui.labelMemUsage.setText('Memory Usage: '+str(totalmem*percentmembusy/100)+' GB of '+totalmemstr) # print "Total Mem str: ",totalmemstr # update system tab if self.ui.tabWidget.currentIndex() == config.SYST_TAB: #determine the computer uptime if config.psutilVer == 1: uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.BOOT_TIME)) else: uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())) self.ui.labelUptime.setText("System Uptime: "+uptime) #update the number of users each time interval as well userInfo=psutil.get_users() if config.psutilVer == 1 else psutil.users() lst=[] for item in userInfo: lst.append(item.name) uusers=set(lst) Nuusers=len(uusers) self.ui.labelNUsers.setText("Number of Users Logged On: "+str(Nuusers)) #determine "Me" user CPU and memory statistics Me=getpass.getuser() cpupctMe=0 memValMe=0 cpupctTot=0 memValTot=0 for proc in psutil.process_iter(): try: #check if process still exists, if so, update dictionaries cpupct=proc.get_cpu_percent(interval=0) if config.psutilVer == 1 else proc.cpu_percent(interval=0) memVal=proc.get_memory_percent() if config.psutilVer == 1 else proc.memory_percent() try: #some processes give permission denied when getting the name, if so, fail out gracefully using this try. if config.psutilVer == 1: uname=proc.username else: uname=proc.username() #print "proc.username: "******" type: ",type(uname)," Me: ",Me," type: ",type(Me) except: uname='' except: #skip process - case where process no longer exists cpupct=0 memVal=0 uname='' cpupctTot+=cpupct memValTot+=memVal #print "uname: ",uname," Me: ",Me #note that on Windows systems that getpass.getuser() does not return the same base username as proc.username, so check for the smaller if Me in uname: cpupctMe+=cpupct memValMe+=memVal #print "cpupctMe: ",cpupctMe," memValMe: ",memValMe #update first position with most recent value overwriting oldest value which has been shifted to first position self.ui.cpu=np.roll(self.ui.cpu,1) #check if CPU smoothing to be applied sm=int(str(self.ui.comboBoxCPUHistSmooth.currentText())) if sm == 1: self.ui.cpu[0]=percentcpubusy elif sm >1: self.ui.cpu[0]=(percentcpubusy+np.sum(self.ui.cpu[1:sm]))/sm else: #unknown case - default to no smoothing self.ui.cpu[0]=percentcpubusy #update progress bar with (potentially) smoothed cpu percentage self.ui.progressBarStatusCPU.setValue(round(self.ui.cpu[0])) self.ui.mem=np.roll(self.ui.mem,1) self.ui.mem[0]=percentmembusy self.ui.cpuMe=np.roll(self.ui.cpuMe,1) #check if CPU smoothing to be applied if sm == 1: self.ui.cpuMe[0]=cpupctMe/(Ncpus) elif sm>1: self.ui.cpuMe[0]=(cpupctMe/(Ncpus)+np.sum(self.ui.cpuMe[1:sm]))/sm else: #use no filtering in case sm is unknown (should never happen...) self.ui.cpuMe[0]=cpupctMe/(Ncpus) self.ui.memMe=np.roll(self.ui.memMe,1) self.ui.memMe[0]=memValMe #update the history plot if self.ui.tabWidget.currentIndex() == config.HIST_TAB: #only update history plot if tab is active font = {'family' : 'sans-serif', 'weight' : 'bold', 'size' : config.pltFont+1} matplotlib.rc('font', **font) xtime=range(0,self.ui.Nsamples+1,self.update) Npts=Ndur/self.update plt.figure(self.ui.figure.number) #make plot figure active plt.clf() #clear figure each time for rolling updates to show plt.plot(xtime[0:Npts+1],self.ui.cpu[0:Npts+1],color='Blue',label='CPU: All',linewidth=config.linewidth) plt.plot(xtime[0:Npts+1],self.ui.mem[0:Npts+1],color='Green',label='Mem: All',linewidth=config.linewidth) plt.plot(xtime[0:Npts+1],self.ui.cpuMe[0:Npts+1],color='red',label='CPU: '+Me,linewidth=config.linewidth) plt.plot(xtime[0:Npts+1],self.ui.memMe[0:Npts+1],color='cyan',label='Mem: '+Me,linewidth=config.linewidth) plt.title('Composite CPU and Memory Activity',fontsize=config.pltFont+1,fontweight='bold') plt.ylabel('% Used',fontsize=config.pltFont+0.5,fontweight='bold') if self.update == 1: xlab="Seconds with 1 Second Updates" elif self.update == 2: xlab="Seconds with 2 Second Updates" elif self.update == 5: xlab="Seconds with 5 Second Updates" elif self.update == 10: xlab="Seconds with 10 Second Updates" plt.xlabel(xlab,fontsize=config.pltFont+0.5,fontweight='bold') plt.legend(loc="upper right",prop={'size':config.pltFont}) plt.xlim([0,Ndur]) self.ui.canvas.draw() #update the process table if self.ui.tabWidget.currentIndex() == config.PROC_TAB: #only update process table if tab is active updateProcTable(self,config) #update the Users bar chart if self.ui.tabWidget.currentIndex() == config.USER_TAB: #only update bar chart if the tab is active. updateUserChart(self,config)
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Form() #defined from ui_sysmon.py self.ui.setupUi(self) self.ui.parent=parent self.ui.progressBarStatusMemory.setStyleSheet("QProgressBar {width: 25px;border: 1px solid black; border-radius: 3px; background: white;text-align: center;padding: 0px;}" +"QProgressBar::chunk:horizontal {background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #00CCEE, stop: 0.3 #00DDEE, stop: 0.6 #00EEEE, stop:1 #00FFEE);}") self.ui.progressBarStatusCPU.setStyleSheet("QProgressBar {width: 25px;border: 1px solid black; border-radius: 3px; background: white;text-align: center;padding: 0px;}" +"QProgressBar::chunk:horizontal {background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #00CCEE, stop: 0.3 #00DDEE, stop: 0.6 #00EEEE, stop:1 #00FFEE);}") #setup timer to enable periodic events such as status update checks self.ctimer = QtCore.QTimer() self.ctimer.start(2000) #time in mSec - set default update timer cycle to 2 seconds QtCore.QObject.connect(self.ctimer, QtCore.SIGNAL("timeout()"), self.constantUpdate) #update rate actions QtCore.QObject.connect(self.ui.radioButton1Sec, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update1Sec) QtCore.QObject.connect(self.ui.radioButton2Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update2Sec) QtCore.QObject.connect(self.ui.radioButton5Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update5Sec) QtCore.QObject.connect(self.ui.radioButton10Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update10Sec) self.update=2 #set default to 2 seconds update rate #duration actions QtCore.QObject.connect(self.ui.radioButton60Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update60Duration) QtCore.QObject.connect(self.ui.radioButton300Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update300Duration) QtCore.QObject.connect(self.ui.radioButton600Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update600Duration) QtCore.QObject.connect(self.ui.radioButton3600Secs, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.update3600Duration) self.duration=60 #set default plot duration to 60 seconds QtCore.QObject.connect(self.ui.pushButtonUpdate, QtCore.SIGNAL('clicked(bool)'), self.updateProcesses) #Initialize System Tab self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) self.ui.labelComputerName.setText("Computer Name: "+platform.node()) if platform.os.name == 'nt': info=platform.win32_ver() oslabel="Windows "+info[0]+" Version: "+info[1] elif platform.os.name == 'posix': info=platform.linux_distribution() oslabel=info[0]+" Version: "+info[1] elif platform.os.name == 'mac': info=platform.mac_ver() oslabel=info[0]+" Version: "+info[1] else: oslabel=" " self.ui.labelOS.setText("Operating System: "+oslabel) info=platform.uname() self.ui.labelProcFam.setText("Processor Family: "+info[5]) #determine the number of users on the computer userInfo=psutil.get_users() if config.psutilVer==1 else psutil.users() lst=[] for item in userInfo: lst.append(item.name) uusers=set(lst) Nuusers=len(uusers) self.ui.labelNUsers.setText("Number of Users Logged On: "+str(Nuusers)) #determine the computer uptime if config.psutilVer == 1: uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.BOOT_TIME)) else: uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())) self.ui.labelUptime.setText("System Uptime: "+uptime) if config.mplLoaded: #if matplotlib loaded OK, initialize plotting #Initialize History Tab self.ui.tabWidget.setCurrentIndex(config.HIST_TAB) #Place Matplotlib figure within the GUI frame #create drawing canvas # a figure instance to plot on if not re.match('1.[0-1]',matplotlib.__version__): #if not an old version of matplotlib, then use the following command matplotlib.rc_context({'toolbar':False}) #initialize figure 1 and its canvas for cpu and memory history plots self.ui.figure = plt.figure(1) # the Canvas Widget displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.ui.canvas = FigureCanvas(self.ui.figure) layout=QtGui.QVBoxLayout(self.ui.framePlot) layout.addWidget(self.ui.canvas) self.ui.layout=layout #initialize figure 2 and its canvas for user usage bar chart self.ui.figure2 = plt.figure(2) self.ui.canvas2 = FigureCanvas(self.ui.figure2) layout2=QtGui.QVBoxLayout(self.ui.frameBar) layout2.addWidget(self.ui.canvas2) self.ui.layout2=layout2 else: #if matplotlib not loaded, remove the tabs that depend upon it self.removeMPLTabs() #initialize history plot arrays - easier just to initialize these even if not doing plotting in case when matplotlib not available. Nsamples=3600 self.ui.Nsamples=Nsamples #need one extra sample to fill the plotting interval self.ui.cpu=np.zeros(Nsamples+1) self.ui.mem=np.zeros(Nsamples+1) self.ui.dt=[None]*(Nsamples+1) self.ui.cpuMe=np.zeros(Nsamples+1) self.ui.memMe=np.zeros(Nsamples+1) self.ui.tabWidget.setTabsClosable(False) #disable the ability to close tabs once state of matplotlib is handled #initialize the process table self.doUpdates=True #flag for updating the process tab table updateProcTable(self,config) #upon initialization completion, set System tab (first tab on left) as the visible tab self.ui.tabWidget.setCurrentIndex(config.SYST_TAB) #initialize version label self.ui.labelVersion.setText("Version: "+__version__+"_"+psutil.__version__)
def constantUpdateActor(self, config): #set duration number Ndur = self.duration #get current CPU percent busy percentcpubusy = psutil.cpu_percent() percentmembusy = psutil.virtual_memory().percent self.ui.progressBarStatusMemory.setValue(round(percentmembusy)) Ncpus = len(psutil.cpu_percent(percpu=True)) self.ui.Ncpus = Ncpus totalcpustr = 'CPU Count: ' + str(Ncpus) # print "Total CPU str: ",totalcpustr self.ui.labelCPUCount.setText(totalcpustr + ' - CPU Utilization:') totalmem = int( round(float(psutil.virtual_memory().total) / (1024 * 1024 * 1024))) #psutil syntax OK for both versions # print "Total Mem: ",totalmem self.ui.totalmem = totalmem totalmemstr = str(totalmem) + ' GB' self.ui.labelMemUsage.setText('Memory Usage: ' + str(totalmem * percentmembusy / 100) + ' GB of ' + totalmemstr) # print "Total Mem str: ",totalmemstr # update system tab if self.ui.tabWidget.currentIndex() == config.SYST_TAB: #determine the computer uptime if config.psutilVer == 1: uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.BOOT_TIME)) else: uptime = str(datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())) self.ui.labelUptime.setText("System Uptime: " + uptime) #update the number of users each time interval as well userInfo = psutil.get_users( ) if config.psutilVer == 1 else psutil.users() lst = [] for item in userInfo: lst.append(item.name) uusers = set(lst) Nuusers = len(uusers) self.ui.labelNUsers.setText("Number of Users Logged On: " + str(Nuusers)) #determine "Me" user CPU and memory statistics Me = getpass.getuser() cpupctMe = 0 memValMe = 0 cpupctTot = 0 memValTot = 0 for proc in psutil.process_iter(): try: #check if process still exists, if so, update dictionaries cpupct = proc.get_cpu_percent( interval=0) if config.psutilVer == 1 else proc.cpu_percent( interval=0) memVal = proc.get_memory_percent( ) if config.psutilVer == 1 else proc.memory_percent() try: #some processes give permission denied when getting the name, if so, fail out gracefully using this try. if config.psutilVer == 1: uname = proc.username else: uname = proc.username() #print "proc.username: "******" type: ",type(uname)," Me: ",Me," type: ",type(Me) except: uname = '' except: #skip process - case where process no longer exists cpupct = 0 memVal = 0 uname = '' cpupctTot += cpupct memValTot += memVal #print "uname: ",uname," Me: ",Me #note that on Windows systems that getpass.getuser() does not return the same base username as proc.username, so check for the smaller if Me in uname: cpupctMe += cpupct memValMe += memVal #print "cpupctMe: ",cpupctMe," memValMe: ",memValMe #update first position with most recent value overwriting oldest value which has been shifted to first position self.ui.cpu = np.roll(self.ui.cpu, 1) #check if CPU smoothing to be applied sm = int(str(self.ui.comboBoxCPUHistSmooth.currentText())) if sm == 1: self.ui.cpu[0] = percentcpubusy elif sm > 1: self.ui.cpu[0] = (percentcpubusy + np.sum(self.ui.cpu[1:sm])) / sm else: #unknown case - default to no smoothing self.ui.cpu[0] = percentcpubusy #update progress bar with (potentially) smoothed cpu percentage self.ui.progressBarStatusCPU.setValue(round(self.ui.cpu[0])) self.ui.mem = np.roll(self.ui.mem, 1) self.ui.mem[0] = percentmembusy self.ui.cpuMe = np.roll(self.ui.cpuMe, 1) #check if CPU smoothing to be applied if sm == 1: self.ui.cpuMe[0] = cpupctMe / (Ncpus) elif sm > 1: self.ui.cpuMe[0] = (cpupctMe / (Ncpus) + np.sum(self.ui.cpuMe[1:sm])) / sm else: #use no filtering in case sm is unknown (should never happen...) self.ui.cpuMe[0] = cpupctMe / (Ncpus) self.ui.memMe = np.roll(self.ui.memMe, 1) self.ui.memMe[0] = memValMe #update the history plot if self.ui.tabWidget.currentIndex() == config.HIST_TAB: #only update history plot if tab is active font = { 'family': 'sans-serif', 'weight': 'bold', 'size': config.pltFont + 1 } matplotlib.rc('font', **font) xtime = range(0, self.ui.Nsamples + 1, self.update) Npts = Ndur / self.update plt.figure(self.ui.figure.number) #make plot figure active plt.clf() #clear figure each time for rolling updates to show plt.plot(xtime[0:Npts + 1], self.ui.cpu[0:Npts + 1], color='Blue', label='CPU: All', linewidth=config.linewidth) plt.plot(xtime[0:Npts + 1], self.ui.mem[0:Npts + 1], color='Green', label='Mem: All', linewidth=config.linewidth) plt.plot(xtime[0:Npts + 1], self.ui.cpuMe[0:Npts + 1], color='red', label='CPU: ' + Me, linewidth=config.linewidth) plt.plot(xtime[0:Npts + 1], self.ui.memMe[0:Npts + 1], color='cyan', label='Mem: ' + Me, linewidth=config.linewidth) plt.title('Composite CPU and Memory Activity', fontsize=config.pltFont + 1, fontweight='bold') plt.ylabel('% Used', fontsize=config.pltFont + 0.5, fontweight='bold') if self.update == 1: xlab = "Seconds with 1 Second Updates" elif self.update == 2: xlab = "Seconds with 2 Second Updates" elif self.update == 5: xlab = "Seconds with 5 Second Updates" elif self.update == 10: xlab = "Seconds with 10 Second Updates" plt.xlabel(xlab, fontsize=config.pltFont + 0.5, fontweight='bold') plt.legend(loc="upper right", prop={'size': config.pltFont}) plt.xlim([0, Ndur]) self.ui.canvas.draw() #update the process table if self.ui.tabWidget.currentIndex() == config.PROC_TAB: #only update process table if tab is active updateProcTable(self, config) #update the Users bar chart if self.ui.tabWidget.currentIndex() == config.USER_TAB: #only update bar chart if the tab is active. updateUserChart(self, config)
def get_user_node(): user_count = RunnableNode('count', method=lambda: (len([x.name for x in ps.get_users()]), 'c')) user_list = RunnableNode('list', method=lambda: ([x.name for x in ps.get_users()], 'name')) return ParentNode('user', children=[user_count, user_list])
def users(self): return psutil.get_users()
def users(oin, env): for item in psutil.get_users(): yield dictify(item)
disk_mountpoints.append(tmp) disk_logical = Node(u'logical', children=disk_mountpoints) disk_physical = Node(u'phyical', children=disk_counters) disk = Node(u'disk', children=(disk_physical, disk_logical)) if_children = [make_if_nodes(x) for x in list(ps.net_io_counters(pernic=True).keys())] interface = Node(u'interface', children=if_children) plugin = Node(u'plugin', method=lambda: [x for x in os.listdir(plugins) if os.path.isfile(os.path.normpath(u'%s/%s') % (plugins, x))]) agent = Node(u'agent', children=(plugin,)) user_count = Node(u'count', method=lambda: (len([x.name for x in ps.get_users()]), u'c')) user_list = Node(u'list', method=lambda: [x.name for x in ps.get_users()]) process = ProcessNode(u'process') service = ServiceNode(u'service') user = Node(u'user', children=(user_count, user_list)) root = Node(u'root', children=(cpu, memory, disk, interface, agent, user, process, service, system)) def getter(accessor=u'', s_plugins=u''): global plugins logging.debug(u"Using %s" % s_plugins) plugins = s_plugins path = [x for x in accessor.split(u'/') if x] if len(path) > 0 and path[0] == u'api':
def generateVal(): userList = psutil.get_users() # Note: this doesn't handle users logged in multiple times very well. return dict([(val.name, dict(zip(userList[i]._fields, list(userList[i])))) for i, val in enumerate(userList)])
## this programm reads and prints system varibles using ## ## -- psutil from Giampaolo Rodola' -- ## ########################################################## import psutil __version__ = "ver. 1.0 - beta" __date__ = 2013, 7, 28 print("-- for help type -- info --") new = input(" what do you wanna know about the system?: ") ############################################################################## ## memory ## memo = psutil.virtual_memory() swap = psutil.swap_memory() ## systm ## user = psutil.get_users() boot = psutil.get_boot_time() syst = psutil.get_pid_list() sysl = psutil.get_process_list() ## cpu ## cpus = psutil.NUM_CPUS cpuc = psutil.cpu_percent(interval=1, percpu=True) cpuv = psutil.cpu_times(percpu=True) ## network ## netw = psutil.network_io_counters() nets = psutil.network_io_counters(pernic=True) ## disk ## dska = psutil.disk_partitions(all=False) dskb = psutil.disk_io_counters(perdisk=False) dskm = psutil.disk_io_counters(perdisk=True) dskc = psutil.disk_usage("C:")
return hdd while 1: print("\n\t--== DT SERVER MONITORING--==\n") print("\tCPU Usage:\t"+dtCPU()+"%") print("\tRAM Usage:\t"+dtMemory()+"%") print("\tHDD Usage:\t"+dtHDD()+"%\n") network = psutil.network_io_counters() bytessend = network[0] bytesrecv = network[1] packsend = network[2] packrecv = network[3] uptime = psutil.get_users() uptime = uptime[0] upstart = uptime[3] upstop = time.time() secalive = upstop-upstart BSsec = bytessend/secalive BRsec = bytesrecv/secalive BSsec = str(round(BSsec/1024,2)) BRsec = str(round(BRsec/1024,2)) mbout = str(round(bytessend/1024,2)) mbin = str(round(bytesrecv/1024,2))
#coding=utf-8 import psutil print psutil.cpu_count(logical=False) b = psutil.pids() for a in b: print a c = psutil.process_iter() #打印进程 for d in c: print d print psutil.get_users() disk = psutil.disk_partitions(all=True) print disk device = disk[0].device print psutil.disk_usage("d:/") import sys print sys.path
def _get_sys_info(self): '''This will populate some basic system information ### INPUT OTHER THAN INTEGERS IS CURRENLTLY NOT SUPPORTED BY NEW RELIC ###''' try: #self.metric_data['Component/System Information/Kernel[string]'] = self.kernel #self.metric_data['Component/System Information/Arch[string]'] = self.arch #self.metric_data['Component/System Information/Boot Time[datetime]'] = self._get_boottime() self.metric_data['Component/System Information/Process Count[process]'] = len(psutil.get_pid_list()) self.metric_data['Component/System Information/Core Count[core]'] = psutil.NUM_CPUS self.metric_data['Component/System Information/Active Sessions[session]'] = len(psutil.get_users()) except Exception, e: loging.exception(e) pass
def collect_userinfo(dirname): logging.info("Collecting user information") with open('%s/users' % (dirname), 'w') as outfile: outfile.write(''.join(_pretty(psutil.get_users())))
def update_users(self): self.clear() for u in psutil.get_users(): self.add(u.name)
def qtde_logados(): ''' Retorna a quantidade de usuarios logados no sistema ate o momento. ''' return json.dumps({"qtde_logados": len((set([u[0] for u in psutil.get_users()])))})
def output_sys_z(sysz): return psutil.get_users()
__version__ = 'ver. 2 - linux' __date__ = 2013, 8, 3 ##################################################### ## cpu ## cpus = psutil.NUM_CPUS cpul = psutil.cpu_percent(interval=1, percpu=True) cpuv = psutil.cpu_times(percpu=True) ## memory ## mema = psutil.virtual_memory() memw = psutil.swap_memory() ## disk ## dskc = psutil.disk_usage("/root/") dskd = psutil.disk_usage("/") ## systm ## sysz = psutil.get_users() sysy = psutil.get_boot_time() sysr = psutil.get_pid_list() sysh = psutil.get_process_list() ## network ## netn = psutil.network_io_counters() netm = psutil.network_io_counters(pernic=True) ##################################################### def print_options(): print("Options:") print(" CPU info's") print(" 'l' cpu load in %") print(" 's' cpu's in systm") print(" 'v' cpu load") print(" RAM info's") print(" 'a' ram info")
def qtde_logados(): ''' Retorna a quantidade de usuarios logados no sistema ate o momento. ''' return json.dumps( {"qtde_logados": len((set([u[0] for u in psutil.get_users()])))})