psutil是一個跨平臺庫(http://code.google.com/p/psutil/),可以輕 鬆實現獲取系統運行的進程和系統利用率(包括CPU、內存、磁盤、網 絡等)信息。它主要應用於系統監控,分析和限制系統資源及進程的管 理。它實現了同等命令行工具提供的功能,如ps、top、lsof、netstat、 ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、 pidof、tty、taskset、pmap等。目前支持32位和64位的Linux、 Windows、OS X、FreeBSD和Sun Solaris等操做系統,支持從2.4到3.4的 Python版本,目前最新版本爲2.0.0。python
一般咱們獲取操做系統信息每每採 用編寫shell來實現,如獲取當前物理內存總大小及已使用大小,shell命 令以下:linux
相比較而言,使用psutil庫實現則更加簡單明瞭。psutil大小單位一 般都採用字節,以下:ios
採集系統的基本性能信息包括CPU、內存、磁盤、網絡等,能夠 完整描述當前系統的運行狀態及質量。psutil模塊已經封裝了這些方法, 用戶能夠根據自身的應用場景,調用相應的方法來知足需求,很是簡單 實用。git
User Time,執行用戶進程的時間百分比; ·github
System Time,執行內核進程和中斷的時間百分比; ·shell
Wait IO,因爲IO等待而使CPU處於idle(空閒)狀態的時間百分 比; ·緩存
Idle,CPU處於idle狀態的時間百分比。網絡
咱們使用Python的psutil.cpu_times()方法能夠很是簡單地獲得這 些信息,同時也能夠獲取CPU的硬件相關信息,好比CPU的物理個數與 邏輯個數,具體見下面的操做例子:運維
獲取所有cpu信息ssh
>>> psutil.cpu_times()
scputimes(user=55.56, nice=0.0, system=28.83, idle=2811.87, iowait=71.64, irq=0.0, softirq=0.4, steal=0.0, guest=0.0, guest_nice=0.0)
獲取cpu某個指標的cpu 信息
>>> psutil.cpu_times().user #cpu用戶時間百分比 57.08 >>> psutil.cpu_count() #邏輯cpu的數量 1 >>> psutil.cpu_count(logical=False) #物理cpu的數量 1
Linux系統的內存利用率信息涉及total(內存總數)、used(已使 用的內存數)、free(空閒內存數)、buffers(緩衝使用數)、 cache(緩存使用數)、swap(交換分區使用數)等,分別使用 psutil.virtual_memory()與psutil.swap_memory()方法獲取這些信 息,具體見下面的操做例子:
獲取所有內存信息
>>> mem=psutil.virtual_memory() >>> mem svmem(total=1928081408, available=1635614720, percent=15.2, used=117481472, free=1023430656, active=433111040, inactive=346320896, buffers=55558144, cached=731611136, shared=524288, slab=91049984)
獲取內存某個指標信息
>>> mem.total #總內存 1928081408 >>> mem.free #空閒內存 1023430656 >>> psutil.swap_memory() #swap分區信息 sswap(total=0, used=0, free=0, percent=0.0, sin=0, sout=0)
在系統的全部磁盤信息中,咱們更加關注磁盤的利用率及IO信 息,其中磁盤利用率使用psutil.disk_usage方法獲取。磁盤IO信息包括 read_count(讀IO數)、write_count(寫IO數)、read_bytes(IO讀字節 數)、write_bytes(IO寫字節數)、read_time(磁盤讀時間)、 write_time(磁盤寫時間)等。這些IO信息可使用 psutil.disk_io_counters()獲取,具體見下面的操做例子:
>>> psutil.disk_partitions() #獲取磁盤的掛載信息 [sdiskpart(device='/dev/vda1', mountpoint='/', fstype='ext4', opts='rw,noatime,data=ordered')] >>> psutil.disk_usage('/') #獲取根目錄的磁盤使用狀況 sdiskusage(total=52709261312, used=1797283840, free=48210923520, percent=3.6) >>> psutil.disk_io_counters() #獲取磁盤總體io的信息 sdiskio(read_count=17654, write_count=16921, read_bytes=336112640, write_bytes=1199091712, read_time=94260, write_time=2551193, read_merged_count=251, write_merged_count=12212, busy_time=111944) >>> psutil.disk_io_counters(perdisk=True) #更細粒度的獲取每塊盤的磁盤io信息 {'vda': sdiskio(read_count=16442, write_count=17139, read_bytes=296236032, write_bytes=1200701440, read_time=93595, write_time=2554037, read_merged_count=251, write_merged_count=12330, busy_time=111885), 'sr0': sdiskio(read_count=1212, write_count=0, read_bytes=39876608, write_bytes=0, read_time=665, write_time=0, read_merged_count=0, write_merged_count=0, busy_time=513), 'loop0': sdiskio(read_count=0, write_count=0, read_bytes=0, write_bytes=0, read_time=0, write_time=0, read_merged_count=0, write_merged_count=0, busy_time=0), 'vda1': sdiskio(read_count=16412, write_count=16436, read_bytes=295162880, write_bytes=1200701440, read_time=93521, write_time=2552650, read_merged_count=251, write_merged_count=12330, busy_time=110707)}
系統的網絡信息與磁盤IO相似,涉及幾個關鍵點,包括 bytes_sent(發送字節數)、bytes_recv=28220119(接收字節數)、 packets_sent=200978(發送數據包數)、packets_recv=212672(接收數 據包數)等。這些網絡信息使用psutil.net_io_counters()方法獲取,具 體見下面的操做例子:
>>> psutil.net_io_counters() #使用psutil.net_io_counters獲取網絡總的IO信 息,默人pernic=False snetio(bytes_sent=3097792, bytes_recv=84277258, packets_sent=30395, packets_recv=76803, errin=0, errout=0, dropin=0, dropout=0) >>> psutil.net_io_counters(pernic=True) #pernic=True獲取每一個網絡接口的網絡io信息 {'lo': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0), 'eth0': snetio(bytes_sent=3151297, bytes_recv=84313463, packets_sent=30879, packets_recv=77288, errin=0, errout=0, dropin=0, dropout=0)}
除了前面介紹的幾個獲取系統基本信息的方法,psutil模塊還支持 獲取用戶登陸、開機時間等信息,具體見下面的操做例子:
>>> psutil.users() [suser(name='root', terminal='pts/0', host='58.101.51.163', started=1556753152.0, pid=10408), suser(name='root', terminal='pts/1', host='58.101.51.163', started=1556755328.0, pid=13692)]
>>> import psutil,datetime >>> psutil.boot_time() #系統開機時間,時間戳的形式 1556752934.0 >>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") #格式轉化成天然時間 '2019-05-02 07:22:14'
系統進程管理方法 得到當前系統的進程信息,可讓運維人員得知應用程序的運行 狀態,包括進程的啓動時間、查看或設置CPU親和度、內存使用率、IO 信息、socket鏈接、線程數等,這些信息能夠呈現出指定進程是否存 活、資源利用狀況,爲開發人員的代碼優化、問題定位提供很好的數據 參考。
(1)進程信息 psutil模塊在獲取進程信息方面也提供了很好的支持,包括使用 psutil.pids()方法獲取全部進程PID,使用psutil.Process()方法獲取 單個進程的名稱、路徑、狀態、系統資源利用率等信息,具體見下面的 操做例子:
>>> import psutil >>> psutil.pids() #列出全部進程PID [1, 2, 3, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 27, 28, 29, 30, 38, 39, 40, 41, 42, 43, 56, 102, 221, 228, 229, 230, 231, 233, 234, 238, 253, 254, 328, 358, 360, 443, 468, 470, 473, 474, 476, 679, 783, 858, 864, 879, 880, 1240, 3015, 3304, 3576, 3586, 3587, 9028, 9119, 10387, 10408, 13377, 13690, 13692, 18041, 18450, 18874, 18947] >>> p=psutil.Process(10387) #實例化一個Process對象,參數爲一進程PID >>> p.name() #進程名 'sshd' >>> p.exe() #進程執行路徑 '/usr/sbin/sshd' >>> p.cwd() #進程工做目錄絕對路徑 '/'
>>> p.status() #進程狀態
'sleeping'
>>> p.create_time() #進程建立時間,時間戳格式 1556753100.62 >>> p.uids() #進程uid信息 puids(real=0, effective=0, saved=0) >>> p.gids() #進程gid信息 pgids(real=0, effective=0, saved=0) >>> p.cpu_times() #進程CPU時間信息,包括user、system兩個CPU時間 pcputimes(user=0.11, system=0.18, children_user=0.0, children_system=0.0) >>> p.memory_percent() #進程內存利用率 0.28764262634288107 >>> p.io_counters() #進程IO信息,包括讀寫IO數及字節數 pio(read_count=4335, write_count=3971, read_bytes=0, write_bytes=0, read_chars=403466, write_chars=301488) >>> p.connections() #返回打開進程socket的namedutples列表,包括fs、family、 laddr [pconn(fd=3, family=2, type=1, laddr=addr(ip='172.27.0.7', port=22), raddr=addr(ip='58.101.51.163', port=38431), status='ESTABLISHED')] >>> p.num_threads() #進程開啓的線程數 1
#進程開啓的線程數
psutil提供的popen類的做用是獲取用戶啓動的應用程序進程信息, 以便跟蹤程序進程的運行狀態。具體實現方法以下:
>>> import psutil >>> from subprocess import PIPE >>> p=psutil.Popen(["/usr/bin/python","-c" "print ('hello')"],stdout=PIPE) >>> p.name() 'python' >>> p.username() 'root' >>> p.communicate() ('hello\n', None) >>> p.cpu_times() #獲得進程運行的CPU時間 pcputimes(user=0.01, system=0.0, children_user=0.0, children_system=0.0)
>>> dir(psutil) ['AF_LINK', 'AIX', 'AccessDenied', 'BSD', 'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED', 'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN', 'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT', 'Error', 'FREEBSD', 'IOPRIO_CLASS_BE', 'IOPRIO_CLASS_IDLE', 'IOPRIO_CLASS_NONE', 'IOPRIO_CLASS_RT', 'LINUX', 'MACOS', 'NETBSD', 'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN', 'NoSuchProcess', 'OPENBSD', 'OSX', 'POSIX', 'POWER_TIME_UNKNOWN', 'POWER_TIME_UNLIMITED', 'PROCFS_PATH', 'Popen', 'Process', 'RLIMIT_AS', 'RLIMIT_CORE', 'RLIMIT_CPU', 'RLIMIT_DATA', 'RLIMIT_FSIZE', 'RLIMIT_LOCKS', 'RLIMIT_MEMLOCK', 'RLIMIT_MSGQUEUE', 'RLIMIT_NICE', 'RLIMIT_NOFILE', 'RLIMIT_NPROC', 'RLIMIT_RSS', 'RLIMIT_RTPRIO', 'RLIMIT_RTTIME', 'RLIMIT_SIGPENDING', 'RLIMIT_STACK', 'RLIM_INFINITY', 'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED', 'STATUS_PARKED', 'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKING', 'STATUS_ZOMBIE', 'SUNOS', 'TimeoutExpired', 'WINDOWS', 'ZombieProcess', '_LOWEST_PID', '_PY3', '_TOTAL_PHYMEM', '__all__', '__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', '_as_dict_attrnames', '_assert_pid_not_reused', '_common', '_compat', '_cpu_busy_time', '_cpu_times_deltas', '_cpu_tot_time', '_last_cpu_times', '_last_cpu_times_2', '_last_per_cpu_times', '_last_per_cpu_times_2', '_lock', '_pmap', '_ppid_map', '_pprint_secs', '_pslinux', '_psplatform', '_psposix', '_psutil_linux', '_psutil_posix', '_timer', '_wrap_numbers', 'boot_time', 'collections', 'contextlib', 'cpu_count', 'cpu_freq', 'cpu_percent', 'cpu_stats', 'cpu_times', 'cpu_times_percent', 'datetime', 'disk_io_counters', 'disk_partitions', 'disk_usage', 'errno', 'functools', 'getloadavg', 'long', 'net_connections', 'net_if_addrs', 'net_if_stats', 'net_io_counters', 'os', 'pid_exists', 'pids', 'process_iter', 'pwd', 'sensors_battery', 'sensors_fans', 'sensors_temperatures', 'signal', 'subprocess', 'swap_memory', 'sys', 'test', 'threading', 'time', 'users', 'version_info', 'virtual_memory', 'wait_procs']
psutil官網:https://psutil.readthedocs.io/en/latest/
psuti的git:https://github.com/giampaolo/psutil