This article is excerpted Liao Xuefeng the great God Website: https://www.liaoxuefeng.com/wiki/1016959663602400/1183565811281984
In Python scripting to simplify the daily operation and maintenance work is an important use of Python. In Linux, there are many system commands allows us time to monitor the status of system operation, such as ps
, top
, free
and so on. To obtain these information systems, Python can subprocess
call and get the results module. But this is very troublesome, especially to write a lot of parsing code.
Another good way to get system information in Python is using psutil
this third-party modules. As the name suggests, psutil = process and system utilities, system monitoring can be achieved not only by one or two lines of code, you can also cross-platform, supports Linux / UNIX / OSX / Windows, is a system administrator and the operation and maintenance of small indispensable partner essential modules.
Installation psutil
If the Anaconda installation, psutil already available. Otherwise, you need to install by pip at the command line:
$ pip install psutil
Permission denied If you encounter installation fails, add sudo try again.
Get CPU information
Let's CPU to obtain information:
>>> Import psutil >>> psutil.cpu_count () # number of logic the CPU 4 >>> psutil.cpu_count (Logical = False) Physical the CPU core # 2 # 2 illustrates a dual-core hyper-threading, four non-core 4 is Hyper-Threading
User statistics CPU / System / Idle time:
>>> psutil.cpu_times() scputimes(user=10963.31, nice=0.0, system=5138.67, idle=356102.45)
Then achieve a similar top
command CPU usage, refreshed once per second, a total of 10 times:
>>> for x in range(10): ... psutil.cpu_percent(interval=1, percpu=True) ... [14.0, 4.0, 4.0, 4.0] [12.0, 3.0, 4.0, 3.0] [8.0, 4.0, 3.0, 4.0] [12.0, 3.0, 3.0, 3.0] [18.8, 5.1, 5.9, 5.0] [10.9, 5.0, 4.0, 3.0] [12.0, 5.0, 4.0, 5.0] [15.0, 5.0, 4.0, 4.0] [19.0, 5.0, 5.0, 4.0] [9.0, 3.0, 2.0, 3.0]
Get memory information
Use psutil obtain physical and swap memory information, were used:
>>> psutil.virtual_memory() svmem(total=8589934592, available=2866520064, percent=66.6, used=7201386496, free=216178688, active=3342192640, inactive=2650341376, wired=1208852480) >>> psutil.swap_memory() sswap(total=1073741824, used=150732800, free=923009024, percent=14.0, sin=10705981440, sout=40353792)
Returns an integer in units of bytes, it can be seen that the total memory size 8589934592 = 8 GB, have been used 7201386496 = 6.7 GB, the use of 66.6%.
Area size is exchanged 1073741824 = 1 GB.
Get disk information
Can get disk partition, disk usage and disk IO information psutil:
>>> psutil.disk_partitions () # disk partition information [sdiskpart (Device = ' / dev / disk1 ' , the mountpoint = ' / ' , FStype = ' HFS ' , the opts = ' RW, local, the rootfs, dovolfs, Journaled, the multilabel ' )] >>> psutil.disk_usage ( ' / ' ) # disk usage sdiskusage (Total = 998 982 549 504 , used = 390 880 133 120 , = Free 607 840 272 384 , Percent = 39.1 ) >>> psutil.disk_io_counters () # disk IO sdiskio (read_count = 988 513, write_count=274457, read_bytes=14856830464, write_bytes=17509420032, read_time=2228966, write_time=1618405)
It can be seen disk '/'
total capacity is 998982549504 = 930 GB, using 39.1%. File format is HFS, opts
contains rw
express writable, journaled
expressed support for the logs.
Obtaining Network Information
psutil may acquire the network interface and the network connection information:
>>> psutil.net_io_counters () # of bytes read acquiring network / packet number snetio (bytes_sent = 3,885,744,870 , bytes_recv = 10,357,676,702 , packets_sent = 10,613,069 , packets_recv = 10,423,357 , ERRIN = 0 , ERROUT = 0 , DROPIN = 0 , = Dropout 0 ) >>> psutil.net_if_addrs () Gets the network interface information # { ' lo0 ' : [SNIC (Family = <AddressFamily.AF_INET: 2 >, address = ' 127.0.0.1 ' , Netmask = ' 255.0.0.0 ' ), ...], ' EN1 ': [SNIC (Family = <AddressFamily.AF_INET: 2 >, address = ' 10.0.1.80 ' , Netmask = ' 255.255.255.0 ' ), ...], ' en0 ' : [...], ' EN2 ' : [...], ' the bridge0 ' : [...] } >>> psutil.net_if_stats () Get network Interface status # { ' lo0 ' : snicstats (ISUP = True, Duplex = <NicDuplex.NIC_DUPLEX_UNKNOWN: 0 >, = Speed 0 , MTU = 16384 ), ' en0 ': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=1500), 'en1': snicstats(...), 'en2': snicstats(...), 'bridge0': snicstats(...) } 要获取当前网络连接信息,使用net_connections(): >>> psutil.net_connections() Traceback (most recent call last): ... PermissionError: [Errno 1] Operation not permitted During handling of the above exception, another exception occurred: Traceback (most recent call last): ... psutil.AccessDenied: psutil.AccessDenied (pid=3847)
You might get an AccessDenied
error because psutil also go to get information system interface, network connection and get the information you need root privileges, in this case, exit the Python interactive environment, with a sudo
restart:
$ sudo python3 Password: ****** Python 3.6.3 ... on darwin Type "help", ... for more information. >>> import psutil >>> psutil.net_connections() [ sconn(fd=83, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip='::127.0.0.1', port=62911), raddr=addr(ip='::127.0.0.1', port=3306), status='ESTABLISHED', pid=3725), sconn(fd=84, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip='::127.0.0.1', port=62905), raddr=addr(ip='::127.0.0.1', port=3306), status='ESTABLISHED', pid=3725), sconn(fd=93, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip='::', port=8080), raddr=(), status='LISTEN', pid=3725), sconn(fd=103, family=<AddressFamily.AF_INET6: 30>, type=1, laddr=addr(ip='::127.0.0.1', port=62918), raddr=addr(ip='::127.0.0.1', port=3306), status='ESTABLISHED', pid=3725), sconn(fd=105, family=<AddressFamily.AF_INET6: 30>, type=1, ..., pid=3725), sconn(fd=106, family=<AddressFamily.AF_INET6: 30>, type=1, ..., pid=3725), sconn(fd=107, family=<AddressFamily.AF_INET6: 30>, type=1, ..., pid=3725), ... sconn(fd=27, family=<AddressFamily.AF_INET: 2>, type=2, ..., pid=1) ]
To get process information
You can get all the details of the process by psutil:
>>> psutil.pids () All processes # ID [ 1-3865 , 3864 , 3863 , 3856 , 3855 , 3853 , 3776 , ..., 45 , 44 is , . 1 , 0 ] >>> psutil.Process = P ( 3776 ) # = Gets the process ID 3776 , in fact, is the current Python interactive environment >>> p.name () # process name ' python3.6 ' >>> p.exe () # process exe path ' / the Users / Michael / anaconda3 / bin / python3.6 ' >>> p.cwd () # process working directory '/Users/michael' >>> p.cmdline () command to start the process # [ ' to python3 ' ] >>> p.ppid () # parent process ID 3765 >>> p.parent () # parent <psutil.Process (pid = 3765 , name = ' the bash ' ) AT 4503144040 > >>> p.children () list of sub-process # [] >>> p.status () process state # ' running ' >>> p.username () process # user name ' Michael ' >>> p.create_time () # process creation time 1511052731.120333 >>>p.terminal () # terminal process '/ dev / ttys002 ' >>> the CPU time p.cpu_times () # process uses pcputimes (User = 0.081150144 , System = .053269812 , children_user = 0.0 , children_system = 0.0 ) >>> p.memory_info () # Process memory PMEM (rss = 8,310,784 , VMS = 2481725440 , pfaults = 3207 , pageins = 18 ) >>> p.open_files () # process open file [] >>> p.connections () # processes associated Fi [] >> > the number of threads p.num_threads () # process 1 >>> p.threads () # all threads information [pthread (id= . 1 , user_time = .090318 , SYSTEM_TIME = .062736 )] >>> p.environ () process environment variables # { ' the SHELL ' : ' / bin / the bash ' , ' the PATH ' : ' / usr / local / bin: / usr / bin: / bin: / usr / sbin: / sbin: ... ' , ' the PWD ' : ' / the Users / Michael ' , ' the LANG ' : ' zh_CN.UTF-. 8 ' , ...} >>> P .terminate () # end process Terminated:15<- own up to the end of his time process and obtain a network connection is similar to a root user needs to obtain root privileges, start the Python interactive environment or .py file, you need sudo privileges. psutil also provides a test () function, can simulate the effect of the ps command: $ sudo python3 Password: ****** Python 3.6 . 3 ... ON darwin Type " Help " , ... for More Information. >>> Import psutil >>> psutil.test () the USER PID % MEM TTY RSS VSZ the START the TIME the COMMAND root 0 24.0 74,270,628 2.01638 million Nov18? 40 : 51 kernel_task root 1 0.1 2494140 9484 ? Nov18 01:39 launchd root 44 0.4 2519872 36404 ? Nov18 02:02 UserEventAgent root 45 ? 2474032 1516 ? Nov18 00:14 syslogd root 47 0.1 2504768 8912 ? Nov18 00:03 kextd root 48 0.1 2505544 4720 ? Nov18 00 : 19 fseventsd appleeven 52 0.1 2499748 5024 ? Nov18 00 : 00 appleeventsd in to the root , with 53 0.1 2500592 6132 ? Nov18 00 : 02 configd ...
summary
psutil such Python program information acquiring system becomes easy.
psutil can also get a lot of useful information systems user information, Windows services, and other details, please refer psutil official website: https://github.com/giampaolo/psutil