通过 运用 Python 第三方 系统 基础 模块, 可以 轻松 获取 服务 关键 运营 指标 数据,包括 Linux 基本 性能、 块 设备、 网卡 接口、 系统 信息、 网络 地址 库 等 信息。 在 采集 到这 些 数据 后, 我们 就可以全方位 了解 系统 服务 的 状态,再结合 告警 机制, 可以 在 第一 时间 响应, 将 异常 出现 在 苗头 时 就得 以 处理。

1 查看是否安装python

Last login: Thu Oct 22 09:28:13 2015 from 192.168.102.252
-bash-3.2$ python
Python 2.4.3 (#1, Jun 11 2009, 14:09:37) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> copyright
Copyright (c) 2001-2006 Python Software Foundation.
All Rights Reserved.

2 安装psutil  模块

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 版本。请选择适合自己的版本

下载地址  https://pypi.python.org/pypi/psutil/

以下是安装步骤 (附录二有各操作系统平台的安装方法

[root@localhost oracle]# cd /peter/

[root@localhost peter]# ls
jdk-6u22-linux-i586-rpm.bin  mnt  netlog  netlog.1124  psutil-2.0.0.tar.gz  rkhunter-1.4.2  rkhunter-1.4.2.tar.gz
[root@localhost peter]# ll
total 688
-rwxrwxrwx 1 root root 163840 Jan 20  2014 jdk-6u22-linux-i586-rpm.bin
drwxr-xr-x 2 root root   4096 Nov 11  2014 mnt
-rw-r--r-- 1 root root  13369 Nov  4  2014 netlog
-rw-r--r-- 1 root root  14568 Nov 24  2014 netlog.1124
-rwxrwxrwx 1 root root 207168 Nov 26  2015 psutil-2.0.0.tar.gz
drwxr-xr-x 3 root root   4096 Mar 13  2014 rkhunter-1.4.2

-rwxrwxrwx 1 root root 277707 Apr  1  2015 rkhunter-1.4.2.tar.gz

[root@localhost peter]# tar -zxvf psutil-2.0.0.tar.gz            ####此处解压
psutil-2.0.0/
psutil-2.0.0/README
psutil-2.0.0/PKG-INFO
psutil-2.0.0/MANIFEST.in
psutil-2.0.0/HISTORY
psutil-2.0.0/TODO
psutil-2.0.0/make.bat
psutil-2.0.0/examples/
psutil-2.0.0/examples/meminfo.py
psutil-2.0.0/examples/disk_usage.py
psutil-2.0.0/examples/iotop.py
psutil-2.0.0/examples/killall.py
psutil-2.0.0/examples/free.py
psutil-2.0.0/examples/pmap.py
psutil-2.0.0/examples/netstat.py
psutil-2.0.0/examples/who.py
psutil-2.0.0/examples/nettop.py
psutil-2.0.0/examples/top.py
psutil-2.0.0/examples/process_detail.py
psutil-2.0.0/test/
psutil-2.0.0/test/__init__.py
psutil-2.0.0/test/README
psutil-2.0.0/test/test_psutil.py
psutil-2.0.0/test/_osx.py
psutil-2.0.0/test/_bsd.py
psutil-2.0.0/test/_posix.py
psutil-2.0.0/test/_linux.py
psutil-2.0.0/test/_sunos.py
psutil-2.0.0/test/test_memory_leaks.py
psutil-2.0.0/test/_windows.py
psutil-2.0.0/Makefile
psutil-2.0.0/docs/
psutil-2.0.0/docs/README
psutil-2.0.0/docs/_themes/
psutil-2.0.0/docs/_themes/pydoctheme/
psutil-2.0.0/docs/_themes/pydoctheme/static/
psutil-2.0.0/docs/_themes/pydoctheme/static/pydoctheme.css
psutil-2.0.0/docs/_themes/pydoctheme/theme.conf
psutil-2.0.0/docs/_template/
psutil-2.0.0/docs/_template/indexsidebar.html
psutil-2.0.0/docs/_template/indexcontent.html
psutil-2.0.0/docs/_template/page.html
psutil-2.0.0/docs/_template/globaltoc.html
psutil-2.0.0/docs/make.bat
psutil-2.0.0/docs/Makefile
psutil-2.0.0/docs/index.rst
psutil-2.0.0/docs/_static/
psutil-2.0.0/docs/_static/copybutton.js
psutil-2.0.0/docs/_static/logo.png
psutil-2.0.0/docs/_static/sidebar.js
psutil-2.0.0/docs/conf.py
psutil-2.0.0/psutil.egg-info/
psutil-2.0.0/psutil.egg-info/PKG-INFO
psutil-2.0.0/psutil.egg-info/SOURCES.txt
psutil-2.0.0/psutil.egg-info/top_level.txt
psutil-2.0.0/psutil.egg-info/dependency_links.txt
psutil-2.0.0/LICENSE
psutil-2.0.0/setup.py
psutil-2.0.0/CREDITS
psutil-2.0.0/setup.cfg
psutil-2.0.0/psutil/
psutil-2.0.0/psutil/__init__.py
psutil-2.0.0/psutil/_psutil_bsd.c
psutil-2.0.0/psutil/_psutil_posix.c
psutil-2.0.0/psutil/_psutil_common.c
psutil-2.0.0/psutil/_psutil_osx.c
psutil-2.0.0/psutil/_compat.py
psutil-2.0.0/psutil/_common.py
psutil-2.0.0/psutil/_psutil_linux.c
psutil-2.0.0/psutil/_psutil_osx.h
psutil-2.0.0/psutil/_psutil_bsd.h
psutil-2.0.0/psutil/_psosx.py
psutil-2.0.0/psutil/_pssunos.py
psutil-2.0.0/psutil/_psutil_windows.h
psutil-2.0.0/psutil/_psutil_windows.c
psutil-2.0.0/psutil/_psutil_common.h
psutil-2.0.0/psutil/_psutil_sunos.c
psutil-2.0.0/psutil/_psbsd.py
psutil-2.0.0/psutil/_psutil_linux.h
psutil-2.0.0/psutil/arch/
psutil-2.0.0/psutil/arch/osx/
psutil-2.0.0/psutil/arch/osx/process_info.h
psutil-2.0.0/psutil/arch/osx/process_info.c
psutil-2.0.0/psutil/arch/windows/
psutil-2.0.0/psutil/arch/windows/ntextapi.h
psutil-2.0.0/psutil/arch/windows/security.c
psutil-2.0.0/psutil/arch/windows/process_info.h
psutil-2.0.0/psutil/arch/windows/process_info.c
psutil-2.0.0/psutil/arch/windows/process_handles.c
psutil-2.0.0/psutil/arch/windows/glpi.h
psutil-2.0.0/psutil/arch/windows/security.h
psutil-2.0.0/psutil/arch/windows/process_handles.h
psutil-2.0.0/psutil/arch/bsd/
psutil-2.0.0/psutil/arch/bsd/process_info.h
psutil-2.0.0/psutil/arch/bsd/process_info.c
psutil-2.0.0/psutil/_psposix.py
psutil-2.0.0/psutil/_psutil_sunos.h
psutil-2.0.0/psutil/_psutil_posix.h
psutil-2.0.0/psutil/_pslinux.py
psutil-2.0.0/psutil/_pswindows.py
[root@localhost peter]# ll
total 692
-rwxrwxrwx 1 root root 163840 Jan 20  2014 jdk-6u22-linux-i586-rpm.bin
drwxr-xr-x 2 root root   4096 Nov 11  2014 mnt
-rw-r--r-- 1 root root  13369 Nov  4  2014 netlog
-rw-r--r-- 1 root root  14568 Nov 24  2014 netlog.1124
drwxr-xr-x 7 1000 1000   4096 Mar 10  2014 psutil-2.0.0
-rwxrwxrwx 1 root root 207168 Nov 26  2015 psutil-2.0.0.tar.gz
drwxr-xr-x 3 root root   4096 Mar 13  2014 rkhunter-1.4.2
-rwxrwxrwx 1 root root 277707 Apr  1  2015 rkhunter-1.4.2.tar.gz

[root@localhost peter]# 
[root@localhost peter]# cd psutil-2.0.0
[root@localhost psutil-2.0.0]# python setup.py install        ###安装
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.4
creating build/lib.linux-x86_64-2.4/psutil
copying psutil/_psosx.py -> build/lib.linux-x86_64-2.4/psutil
copying psutil/_pssunos.py -> build/lib.linux-x86_64-2.4/psutil
copying psutil/__init__.py -> build/lib.linux-x86_64-2.4/psutil
copying psutil/_pslinux.py -> build/lib.linux-x86_64-2.4/psutil
copying psutil/_psbsd.py -> build/lib.linux-x86_64-2.4/psutil
copying psutil/_compat.py -> build/lib.linux-x86_64-2.4/psutil
copying psutil/_pswindows.py -> build/lib.linux-x86_64-2.4/psutil
copying psutil/_psposix.py -> build/lib.linux-x86_64-2.4/psutil
copying psutil/_common.py -> build/lib.linux-x86_64-2.4/psutil
running build_ext
building '_psutil_linux' extension
creating build/temp.linux-x86_64-2.4
creating build/temp.linux-x86_64-2.4/psutil
gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall
-Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector
--param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fPIC
-I/usr/include/python2.4 -c psutil/_psutil_linux.c -o
build/temp.linux-x86_64-2.4/psutil/_psutil_linux.o
psutil/_psutil_linux.c: In function 'psutil_proc_cpu_affinity_set':
psutil/_psutil_linux.c:327: warning: suggest explicit braces to avoid ambiguous 'else'
gcc -pthread -shared build/temp.linux-x86_64-2.4/psutil/_psutil_linux.o -o build/lib.linux-x86_64-2.4/_psutil_linux.so
building '_psutil_posix' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall
-Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector
--param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fPIC
-I/usr/include/python2.4 -c psutil/_psutil_posix.c -o
build/temp.linux-x86_64-2.4/psutil/_psutil_posix.o
gcc -pthread -shared build/temp.linux-x86_64-2.4/psutil/_psutil_posix.o -o build/lib.linux-x86_64-2.4/_psutil_posix.so
running install_lib
copying build/lib.linux-x86_64-2.4/_psutil_posix.so -> /usr/lib64/python2.4/site-packages
copying build/lib.linux-x86_64-2.4/_psutil_linux.so -> /usr/lib64/python2.4/site-packages
creating /usr/lib64/python2.4/site-packages/psutil
copying build/lib.linux-x86_64-2.4/psutil/_psosx.py -> /usr/lib64/python2.4/site-packages/psutil
copying build/lib.linux-x86_64-2.4/psutil/_pssunos.py -> /usr/lib64/python2.4/site-packages/psutil
copying build/lib.linux-x86_64-2.4/psutil/__init__.py -> /usr/lib64/python2.4/site-packages/psutil
copying build/lib.linux-x86_64-2.4/psutil/_pslinux.py -> /usr/lib64/python2.4/site-packages/psutil
copying build/lib.linux-x86_64-2.4/psutil/_psbsd.py -> /usr/lib64/python2.4/site-packages/psutil
copying build/lib.linux-x86_64-2.4/psutil/_compat.py -> /usr/lib64/python2.4/site-packages/psutil
copying build/lib.linux-x86_64-2.4/psutil/_pswindows.py -> /usr/lib64/python2.4/site-packages/psutil
copying build/lib.linux-x86_64-2.4/psutil/_psposix.py -> /usr/lib64/python2.4/site-packages/psutil
copying build/lib.linux-x86_64-2.4/psutil/_common.py -> /usr/lib64/python2.4/site-packages/psutil
byte-compiling /usr/lib64/python2.4/site-packages/psutil/_psosx.py to _psosx.pyc
byte-compiling /usr/lib64/python2.4/site-packages/psutil/_pssunos.py to _pssunos.pyc
byte-compiling /usr/lib64/python2.4/site-packages/psutil/__init__.py to __init__.pyc
byte-compiling /usr/lib64/python2.4/site-packages/psutil/_pslinux.py to _pslinux.pyc
byte-compiling /usr/lib64/python2.4/site-packages/psutil/_psbsd.py to _psbsd.pyc
byte-compiling /usr/lib64/python2.4/site-packages/psutil/_compat.py to _compat.pyc
byte-compiling /usr/lib64/python2.4/site-packages/psutil/_pswindows.py to _pswindows.pyc
byte-compiling /usr/lib64/python2.4/site-packages/psutil/_psposix.py to _psposix.pyc
byte-compiling /usr/lib64/python2.4/site-packages/psutil/_common.py to _common.pyc
[root@localhost psutil-2.0.0]#

3 进入python 试一下 psutil 模块是否安装正确
#python

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>> import psutil                                                                                                   
>>> psutil.cpu_times()
scputimes(user=7924.96, nice=212.0, system=1933.8,
idle=12099434.460000001, iowait=3665.8400000000001,
irq=83.379999999999995, softirq=491.57999999999998, steal=0.0)

>>> psutil.swap_memory()
sswap(total=8439095296L, used=921686016L, free=7517409280L, percent=10.9, sin=2560000, sout=636985344)
>>> psutil.swap_memory().free
7517409280L
>>>

调用函数: 函数名.参数

后面附函数&参数列表

4  通过一个案例见证以下psutil 的功能

以下通过shell &python实现一个服务器信息的简单监控,执行我做好的脚步

[root@localhost peter]# ./peter.sh 
 开机时间:2015-10-22 09:22:39
 当前CPU使用率:1.9%
 物理内存:7950M        使用率:10.6%
Swap内存:8024M 使用率:10.9%
 发送:12653809 Byte    发送包数:122654个
 接收:5585369078 Byte  接收包数:46197965个
 盘符: /dev/sda3 挂载点: / 使用率: 29.6%
 盘符: /dev/sda5 挂载点: /oracle 使用率: 29.6%
 盘符: /dev/sda2 挂载点: /oracle/oradata 使用率: 42.8%
 盘符: /dev/sda1 挂载点: /boot 使用率: 11.8%
 盘符: /dev/sdb1 挂载点: /oracle/oradata2 使用率: 53.3%
[root@localhost peter]#

下面看一下peter.sh的内容内容,大家直接粘过去就能用。有兴趣的朋友可以自己再优化一下

#!/usr/bin/env python
#coding:utf-8
import psutil
import time
import sys
from optparse import OptionParser
parser = OptionParser()  
parser.add_option("-t", "--time", dest="time",
                  help="此参数可查看当前下载占的带宽,-t是测试时间", metavar="10")  
parser.add_option("-d", "--deamon",action="store_false", dest="deamon", default=True,  
                  help="后台运行此脚本") 
 
def Sysinfo():
    Boot_Start = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(psutil.boot_time()))  
    time.sleep(0.5)
    Cpu_usage = psutil.cpu_percent()
    RAM = int(psutil.virtual_memory().total/(1027*1024))
    RAM_percent = psutil.virtual_memory().percent
    Swap = int(psutil.swap_memory().total/(1027*1024))
    Swap_percent = psutil.swap_memory().percent
    Net_sent = psutil.net_io_counters().bytes_sent
    Net_recv = psutil.net_io_counters().bytes_recv
    Net_spkg = psutil.net_io_counters().packets_sent
    Net_rpkg = psutil.net_io_counters().packets_recv
    BFH = r'%'
    print " \033[1;32m开机时间:%s\033[1;m"  % Boot_Start
    print " \033[1;32m当前CPU使用率:%s%s\033[1;m" % (Cpu_usage,BFH)
    print " \033[1;32m物理内存:%dM\t使用率:%s%s\033[1;m" % (RAM,RAM_percent,BFH)
    print "\033[1;32mSwap内存:%dM\t使用率:%s%s\033[1;m" % (Swap,Swap_percent,BFH)
    print " \033[1;32m发送:%d Byte\t发送包数:%d个\033[1;m" % (Net_sent,Net_spkg)
    print " \033[1;32m接收:%d Byte\t接收包数:%d个\033[1;m" % (Net_recv,Net_rpkg)
 
    for i in psutil.disk_partitions():
        print " \033[1;32m盘符: %s 挂载点: %s 使用率: %s%s\033[1;m" % (i[0],i[1],psutil.disk_usage(i[1])[3],BFH)
 
 
def Net_io(s):
    x = 0
    sum = 0
    while True:
        if x >= s:
            break
        r1 = psutil.net_io_counters().bytes_recv
        time.sleep(1)
        r2 = psutil.net_io_counters().bytes_recv
        y = r2 - r1
        print "%.2f Kb/s" % (y / 1024.0)
        sum += y
        x += 1
    result = sum / x
    print "\033[1;32m%s秒内平均速度:%.2f Kb/s \033[1;m"  % (x,result / 1024.0)
if __name__ == "__main__":
    (options, args) = parser.parse_args()  
    if options.time:
        Net_io(int(options.time))
    else:
        Sysinfo()

######脚本至此结束

附录1  psutil 模块的其它用法:

Example usages

CPU

  1. >>> import psutil
  2. >>> psutil.cpu_times()
  3. scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, nice=0.0)
  4. >>>
  5. >>> for x in range(3):
  6. ... psutil.cpu_percent(interval=1)
  7. ...
  8. 4.0
  9. 5.9
  10. 3.8
  11. >>>
  12. >>> for x in range(3):
  13. ... psutil.cpu_percent(interval=1, percpu=True)
  14. ...
  15. [4.0, 6.9, 3.7, 9.2]
  16. [7.0, 8.5, 2.4, 2.1]
  17. [1.2, 9.0, 9.9, 7.2]
  18. >>>
  19. >>>
  20. >>> for x in range(3):
  21. ... psutil.cpu_times_percent(interval=1, percpu=False)
  22. ...
  23. scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
  24. scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
  25. scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
  26. >>>
  27. >>> psutil.cpu_count()
  28. 4
  29. >>> psutil.cpu_count(logical=False)
  30. 2
  31. >>>

Memory

  1. >>> psutil.virtual_memory()
  2. svmem(total=8374149120, available=2081050624, percent=75.1, used=8074080256, free=300068864, active=3294920704, inactive=1361616896, buffers=529895424, cached=1251086336)
  3. >>> psutil.swap_memory()
  4. sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944)
  5. >>>

Disks

  1. >>> psutil.disk_partitions()
  2. [sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
  3. sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext, opts='rw')]
  4. >>>
  5. >>> psutil.disk_usage('/')
  6. sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
  7. >>>
  8. >>> psutil.disk_io_counters(perdisk=False)
  9. sdiskio(read_count=719566, write_count=1082197, read_bytes=18626220032, write_bytes=24081764352, read_time=5023392, write_time=63199568)
  10. >>>

Network

  1. >>> psutil.net_io_counters(pernic=True)
  2. {'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0),
  3. 'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)}
  4. >>>
  5. >>> psutil.net_connections()
  6. [pconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=('10.0.0.1', 48776), raddr=('93.186.135.91', 80), status='ESTABLISHED', pid=1254),
  7. pconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=('10.0.0.1', 43761), raddr=('72.14.234.100', 80), status='CLOSING', pid=2987),
  8. pconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=('10.0.0.1', 60759), raddr=('72.14.234.104', 80), status='ESTABLISHED', pid=None),
  9. pconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=('10.0.0.1', 51314), raddr=('72.14.234.83', 443), status='SYN_SENT', pid=None)
  10. ...]
  11. >>>
  12. >>> psutil.net_if_addrs()
  13. {'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
  14. snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
  15. snic(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
  16. 'wlan0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
  17. snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
  18. snic(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
  19. >>>
  20. >>> psutil.net_if_stats()
  21. {'eth0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500),
  22. 'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=65536)}

Other system info

  1. >>> psutil.users()
  2. [user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
  3. user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
  4. >>>
  5. >>> psutil.boot_time()
  6. 1365519115.0
  7. >>>

Process management

  1. >>> import psutil
  2. >>> psutil.pids()
  3. [1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
  4. 268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355,
  5. 2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245,
  6. 4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358,
  7. 4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235,
  8. 5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
  9. >>>
  10. >>> p = psutil.Process(7055)
  11. >>> p.name()
  12. 'python'
  13. >>> p.exe()
  14. '/usr/bin/python'
  15. >>> p.cwd()
  16. '/home/giampaolo'
  17. >>> p.cmdline()
  18. ['/usr/bin/python', 'main.py']
  19. >>>
  20. >>> p.status()
  21. 'running'
  22. >>> p.username()
  23. 'giampaolo'
  24. >>> p.create_time()
  25. 1267551141.5019531
  26. >>> p.terminal()
  27. '/dev/pts/0'
  28. >>>
  29. >>> p.uids()
  30. puids(real=1000, effective=1000, saved=1000)
  31. >>> p.gids()
  32. pgids(real=1000, effective=1000, saved=1000)
  33. >>>
  34. >>> p.cpu_times()
  35. pcputimes(user=1.02, system=0.31)
  36. >>> p.cpu_percent(interval=1.0)
  37. 12.1
  38. >>> p.cpu_affinity()
  39. [0, 1, 2, 3]
  40. >>> p.cpu_affinity([0]) # set
  41. >>>
  42. >>> p.memory_percent()
  43. 0.63423
  44. >>>
  45. >>> p.memory_info()
  46. pmem(rss=7471104, vms=68513792)
  47. >>> p.memory_info_ex()
  48. extmem(rss=9662464, vms=49192960, shared=3612672, text=2564096, lib=0, data=5754880, dirty=0)
  49. >>> p.memory_maps()
  50. [pmmap_grouped(path='/lib/x86_64-linux-gnu/libutil-2.15.so', rss=16384, anonymous=8192, swap=0),
  51. pmmap_grouped(path='/lib/x86_64-linux-gnu/libc-2.15.so', rss=6384, anonymous=15, swap=0),
  52. pmmap_grouped(path='/lib/x86_64-linux-gnu/libcrypto.so.1.0.0', rss=34124, anonymous=1245, swap=0),
  53. pmmap_grouped(path='[heap]', rss=54653, anonymous=8192, swap=0),
  54. pmmap_grouped(path='[stack]', rss=1542, anonymous=166, swap=0),
  55. ...]
  56. >>>
  57. >>> p.io_counters()
  58. pio(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632)
  59. >>>
  60. >>> p.open_files()
  61. [popenfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
  62. >>>
  63. >>> p.connections()
  64. [pconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=('10.0.0.1', 48776), raddr=('93.186.135.91', 80), status='ESTABLISHED'),
  65. pconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=('10.0.0.1', 43761), raddr=('72.14.234.100', 80), status='CLOSING'),
  66. pconn(fd=119, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=('10.0.0.1', 60759), raddr=('72.14.234.104', 80), status='ESTABLISHED'),
  67. pconn(fd=123, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=('10.0.0.1', 51314), raddr=('72.14.234.83', 443), status='SYN_SENT')]
  68. >>>
  69. >>> p.num_threads()
  70. 4
  71. >>> p.num_fds()
  72. 8
  73. >>> p.threads()
  74. [pthread(id=5234, user_time=22.5, system_time=9.2891),
  75. pthread(id=5235, user_time=0.0, system_time=0.0),
  76. pthread(id=5236, user_time=0.0, system_time=0.0),
  77. pthread(id=5237, user_time=0.0707, system_time=1.1)]
  78. >>>
  79. >>> p.num_ctx_switches()
  80. pctxsw(voluntary=78, involuntary=19)
  81. >>>
  82. >>> p.nice()
  83. 0
  84. >>> p.nice(10) # set
  85. >>>
  86. >>> p.ionice(psutil.IOPRIO_CLASS_IDLE) # IO priority (Win and Linux only)
  87. >>> p.ionice()
  88. pionice(ioclass=<IOPriority.IOPRIO_CLASS_IDLE: 3>, value=0)
  89. >>>
  90. >>> p.rlimit(psutil.RLIMIT_NOFILE, (5, 5)) # set resource limits (Linux only)
  91. >>> p.rlimit(psutil.RLIMIT_NOFILE)
  92. (5, 5)
  93. >>>
  94. >>> p.suspend()
  95. >>> p.resume()
  96. >>>
  97. >>> p.terminate()
  98. >>> p.wait(timeout=3)
  99. 0
  100. >>>
  101. >>> psutil.test()
  102. USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND
  103. root 1 0.0 0.0 24584 2240 Jun17 00:00 init
  104. root 2 0.0 0.0 0 0 Jun17 00:00 kthreadd
  105. root 3 0.0 0.0 0 0 Jun17 00:05 ksoftirqd/0
  106. ...
  107. giampaolo 31475 0.0 0.0 20760 3024 /dev/pts/0 Jun19 00:00 python2.4
  108. giampaolo 31721 0.0 2.2 773060 181896 00:04 10:30 chrome
  109. root 31763 0.0 0.0 0 0 00:05 00:00 kworker/0:1
  110. >>>

Further process APIs

  1. >>> for p in psutil.process_iter():
  2. ... print(p)
  3. ...
  4. psutil.Process(pid=1, name='init')
  5. psutil.Process(pid=2, name='kthreadd')
  6. psutil.Process(pid=3, name='ksoftirqd/0')
  7. ...
  8. >>>
  9. >>> def on_terminate(proc):
  10. ... print("process {} terminated".format(proc))
  11. ...
  12. >>> # waits for multiple processes to terminate
  13. >>> gone, alive = psutil.wait_procs(procs_list, 3, callback=on_terminate)
  14. >>>

附录2  各平台安装方法

Installing using pip on UNIX

The easiest way to install psutil on UNIX is by using pip (but first you might need to install python header files; see later). First install pip:

  1. $ wget https://bootstrap.pypa.io/get-pip.py
  2. $ python get-pip.py

...then run:

  1. $ pip install psutil

You may need to install gcc and python header files first (see later).

Installing on Windows

Just get the right installer for your Python version and architecture from: https://pypi.python.org/pypi/psutil/#downloadsSince wheels installers are also available you may also use pip.

Compiling on Windows using Visual Studio

In order to compile psutil on Windows you'll need Visual Studio (Mingw32 is no longer supported). You must have the same version of Visual Studio used to compile your installation of Python, that is:

  1. * Python 2.6: VS 2008 (download it from `here <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_)
  2. * Python 2.7: VS 2008 (download it from `here <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_)
  3. * Python 3.3, 3.4: VS 2010 (you can download it from `MS website <http://www.visualstudio.com/downloads/download-visual-studio-vs#d-2010-express>`_)
  4. * Python 3.5: `VS 2015 UP <http://www.visualstudio.com/en-au/news/vs2015-preview-vs>`_

...then run:

  1. setup.py build

...or:

  1. make.bat build

Compiling 64 bit versions of Python 2.6 and 2.7 with VS 2008 requires Windows SDK and .NET Framework 3.5 SP1 to be installed first. Once you have those run vcvars64.bat, then compile: http://stackoverflow.com/questions/11072521/

Installing on Linux

gcc is required and so the python headers. They can easily be installed by using the distro package manager. For example, on Debian and Ubuntu:

  1. $ sudo apt-get install gcc python-dev

...on Redhat and CentOS:

  1. $ sudo yum install gcc python-devel

Once done, you can build/install psutil with:

  1. $ python setup.py install

Installing on OS X

OS X installation from source will require gcc which you can obtain as part of the 'XcodeTools' installer from Apple. Then you can run the standard distutils commands. To build only:

  1. $ python setup.py build

To install and build:

  1. $ python setup.py install

Installing on FreeBSD

The same compiler used to install Python must be present on the system in order to build modules using distutils. Assuming it is installed, you can build using the standard distutils commands.

Build only:

  1. $ python setup.py build

Install and build:

  1. $ python setup.py install

Makefile

A makefile is available for both UNIX and Windows (make.bat). It provides some automations for the tasks described above and might be preferred over using setup.py. With it you can:

  1. $ make install # just install (in --user mode)
  2. $ make uninstall # uninstall (needs pip)
  3. $ make test # run tests
  4. $ make clean # remove installation files
  5.  
  1. 通过 运用 Python 第三方 系统 基础 模块, 可以 轻松 获取 服务 关键 运营 指标 数据,包括 Linux 基本 性能、 设备、 网卡 接口、 系统 信息、 网络 地址 信息。 采集 到这 数据 后, 我们 就可以全方位 了解 系统 服务 状态,再结合 告警 机制, 可以 第一 时间 响应, 异常 出现 苗头 就得 处理。
  2.  
  3. 查看是否安装python
  4.  
  5. Last login: Thu Oct :: from 192.168.102.252
  6. -bash-3.2$ python
  7. Python 2.4. (#, Jun , ::)
  8. [GCC 4.1. (Red Hat 4.1.-)] on linux2
  9. Type "help", "copyright", "credits" or "license" for more information.
  10. >>> copyright
  11. Copyright (c) - Python Software Foundation.
  12. All Rights Reserved.
  13.  
  14. 安装psutil 模块
  15.  
  16. psutil 一个 平台 库( http:// code. google. com/ p/ psutil/), 能够 轻松 实现 获取 系统 运行 的 进程 和 系统 利用率( 包括 CPU、 内存、 磁盘、 网络 等) 信息。
  17.  
  18. 实现 同等 命令行 工具 提供 功能, ps top lsof netstat ifconfig who df kill free nice ionice iostat iotop uptime pidof tty tasksetpmap 等。目前 支持 Linux Windows OS X FreeBSD Sun Solaris 操作系统, 支持 . . Python 版本。请选择适合自己的版本
  19.  
  20. 下载地址 https://pypi.python.org/pypi/psutil/
  21.  
  22. 以下是安装步骤 (附录二有各操作系统平台的安装方法)
  23.  
  24. [root@localhost oracle]# cd /peter/
  25. [root@localhost peter]# ls
  26. jdk-6u22-linux-i586-rpm.bin mnt netlog netlog. psutil-2.0..tar.gz rkhunter-1.4. rkhunter-1.4..tar.gz
  27. [root@localhost peter]# ll
  28. total
  29. -rwxrwxrwx root root Jan jdk-6u22-linux-i586-rpm.bin
  30. drwxr-xr-x root root Nov mnt
  31. -rw-r--r-- root root Nov netlog
  32. -rw-r--r-- root root Nov netlog.
  33. -rwxrwxrwx root root Nov psutil-2.0..tar.gz
  34. drwxr-xr-x root root Mar rkhunter-1.4.
  35.  
  36. -rwxrwxrwx root root Apr rkhunter-1.4..tar.gz
  37. [root@localhost peter]# tar -zxvf psutil-2.0..tar.gz ####此处解压
  38. psutil-2.0./
  39. psutil-2.0./README
  40. psutil-2.0./PKG-INFO
  41. psutil-2.0./MANIFEST.in
  42. psutil-2.0./HISTORY
  43. psutil-2.0./TODO
  44. psutil-2.0./make.bat
  45. psutil-2.0./examples/
  46. psutil-2.0./examples/meminfo.py
  47. psutil-2.0./examples/disk_usage.py
  48. psutil-2.0./examples/iotop.py
  49. psutil-2.0./examples/killall.py
  50. psutil-2.0./examples/free.py
  51. psutil-2.0./examples/pmap.py
  52. psutil-2.0./examples/netstat.py
  53. psutil-2.0./examples/who.py
  54. psutil-2.0./examples/nettop.py
  55. psutil-2.0./examples/top.py
  56. psutil-2.0./examples/process_detail.py
  57. psutil-2.0./test/
  58. psutil-2.0./test/__init__.py
  59. psutil-2.0./test/README
  60. psutil-2.0./test/test_psutil.py
  61. psutil-2.0./test/_osx.py
  62. psutil-2.0./test/_bsd.py
  63. psutil-2.0./test/_posix.py
  64. psutil-2.0./test/_linux.py
  65. psutil-2.0./test/_sunos.py
  66. psutil-2.0./test/test_memory_leaks.py
  67. psutil-2.0./test/_windows.py
  68. psutil-2.0./Makefile
  69. psutil-2.0./docs/
  70. psutil-2.0./docs/README
  71. psutil-2.0./docs/_themes/
  72. psutil-2.0./docs/_themes/pydoctheme/
  73. psutil-2.0./docs/_themes/pydoctheme/static/
  74. psutil-2.0./docs/_themes/pydoctheme/static/pydoctheme.css
  75. psutil-2.0./docs/_themes/pydoctheme/theme.conf
  76. psutil-2.0./docs/_template/
  77. psutil-2.0./docs/_template/indexsidebar.html
  78. psutil-2.0./docs/_template/indexcontent.html
  79. psutil-2.0./docs/_template/page.html
  80. psutil-2.0./docs/_template/globaltoc.html
  81. psutil-2.0./docs/make.bat
  82. psutil-2.0./docs/Makefile
  83. psutil-2.0./docs/index.rst
  84. psutil-2.0./docs/_static/
  85. psutil-2.0./docs/_static/copybutton.js
  86. psutil-2.0./docs/_static/logo.png
  87. psutil-2.0./docs/_static/sidebar.js
  88. psutil-2.0./docs/conf.py
  89. psutil-2.0./psutil.egg-info/
  90. psutil-2.0./psutil.egg-info/PKG-INFO
  91. psutil-2.0./psutil.egg-info/SOURCES.txt
  92. psutil-2.0./psutil.egg-info/top_level.txt
  93. psutil-2.0./psutil.egg-info/dependency_links.txt
  94. psutil-2.0./LICENSE
  95. psutil-2.0./setup.py
  96. psutil-2.0./CREDITS
  97. psutil-2.0./setup.cfg
  98. psutil-2.0./psutil/
  99. psutil-2.0./psutil/__init__.py
  100. psutil-2.0./psutil/_psutil_bsd.c
  101. psutil-2.0./psutil/_psutil_posix.c
  102. psutil-2.0./psutil/_psutil_common.c
  103. psutil-2.0./psutil/_psutil_osx.c
  104. psutil-2.0./psutil/_compat.py
  105. psutil-2.0./psutil/_common.py
  106. psutil-2.0./psutil/_psutil_linux.c
  107. psutil-2.0./psutil/_psutil_osx.h
  108. psutil-2.0./psutil/_psutil_bsd.h
  109. psutil-2.0./psutil/_psosx.py
  110. psutil-2.0./psutil/_pssunos.py
  111. psutil-2.0./psutil/_psutil_windows.h
  112. psutil-2.0./psutil/_psutil_windows.c
  113. psutil-2.0./psutil/_psutil_common.h
  114. psutil-2.0./psutil/_psutil_sunos.c
  115. psutil-2.0./psutil/_psbsd.py
  116. psutil-2.0./psutil/_psutil_linux.h
  117. psutil-2.0./psutil/arch/
  118. psutil-2.0./psutil/arch/osx/
  119. psutil-2.0./psutil/arch/osx/process_info.h
  120. psutil-2.0./psutil/arch/osx/process_info.c
  121. psutil-2.0./psutil/arch/windows/
  122. psutil-2.0./psutil/arch/windows/ntextapi.h
  123. psutil-2.0./psutil/arch/windows/security.c
  124. psutil-2.0./psutil/arch/windows/process_info.h
  125. psutil-2.0./psutil/arch/windows/process_info.c
  126. psutil-2.0./psutil/arch/windows/process_handles.c
  127. psutil-2.0./psutil/arch/windows/glpi.h
  128. psutil-2.0./psutil/arch/windows/security.h
  129. psutil-2.0./psutil/arch/windows/process_handles.h
  130. psutil-2.0./psutil/arch/bsd/
  131. psutil-2.0./psutil/arch/bsd/process_info.h
  132. psutil-2.0./psutil/arch/bsd/process_info.c
  133. psutil-2.0./psutil/_psposix.py
  134. psutil-2.0./psutil/_psutil_sunos.h
  135. psutil-2.0./psutil/_psutil_posix.h
  136. psutil-2.0./psutil/_pslinux.py
  137. psutil-2.0./psutil/_pswindows.py
  138. [root@localhost peter]# ll
  139. total
  140. -rwxrwxrwx root root Jan jdk-6u22-linux-i586-rpm.bin
  141. drwxr-xr-x root root Nov mnt
  142. -rw-r--r-- root root Nov netlog
  143. -rw-r--r-- root root Nov netlog.
  144. drwxr-xr-x Mar psutil-2.0.
  145. -rwxrwxrwx root root Nov psutil-2.0..tar.gz
  146. drwxr-xr-x root root Mar rkhunter-1.4.
  147. -rwxrwxrwx root root Apr rkhunter-1.4..tar.gz
  148.  
  149. [root@localhost peter]#
  150. [root@localhost peter]# cd psutil-2.0.
  151. [root@localhost psutil-2.0.]# python setup.py install ###安装
  152. running install
  153. running build
  154. running build_py
  155. creating build
  156. creating build/lib.linux-x86_64-2.4
  157. creating build/lib.linux-x86_64-2.4/psutil
  158. copying psutil/_psosx.py -> build/lib.linux-x86_64-2.4/psutil
  159. copying psutil/_pssunos.py -> build/lib.linux-x86_64-2.4/psutil
  160. copying psutil/__init__.py -> build/lib.linux-x86_64-2.4/psutil
  161. copying psutil/_pslinux.py -> build/lib.linux-x86_64-2.4/psutil
  162. copying psutil/_psbsd.py -> build/lib.linux-x86_64-2.4/psutil
  163. copying psutil/_compat.py -> build/lib.linux-x86_64-2.4/psutil
  164. copying psutil/_pswindows.py -> build/lib.linux-x86_64-2.4/psutil
  165. copying psutil/_psposix.py -> build/lib.linux-x86_64-2.4/psutil
  166. copying psutil/_common.py -> build/lib.linux-x86_64-2.4/psutil
  167. running build_ext
  168. building '_psutil_linux' extension
  169. creating build/temp.linux-x86_64-2.4
  170. creating build/temp.linux-x86_64-2.4/psutil
  171. gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE= -fexceptions -fstack-protector --param=ssp-buffer-size= -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fPIC -I/usr/include/python2. -c psutil/_psutil_linux.c -o build/temp.linux-x86_64-2.4/psutil/_psutil_linux.o
  172. psutil/_psutil_linux.c: In function 'psutil_proc_cpu_affinity_set':
  173. psutil/_psutil_linux.c:: warning: suggest explicit braces to avoid ambiguous 'else'
  174. gcc -pthread -shared build/temp.linux-x86_64-2.4/psutil/_psutil_linux.o -o build/lib.linux-x86_64-2.4/_psutil_linux.so
  175. building '_psutil_posix' extension
  176. gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE= -fexceptions -fstack-protector --param=ssp-buffer-size= -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fPIC -I/usr/include/python2. -c psutil/_psutil_posix.c -o build/temp.linux-x86_64-2.4/psutil/_psutil_posix.o
  177. gcc -pthread -shared build/temp.linux-x86_64-2.4/psutil/_psutil_posix.o -o build/lib.linux-x86_64-2.4/_psutil_posix.so
  178. running install_lib
  179. copying build/lib.linux-x86_64-2.4/_psutil_posix.so -> /usr/lib64/python2./site-packages
  180. copying build/lib.linux-x86_64-2.4/_psutil_linux.so -> /usr/lib64/python2./site-packages
  181. creating /usr/lib64/python2./site-packages/psutil
  182. copying build/lib.linux-x86_64-2.4/psutil/_psosx.py -> /usr/lib64/python2./site-packages/psutil
  183. copying build/lib.linux-x86_64-2.4/psutil/_pssunos.py -> /usr/lib64/python2./site-packages/psutil
  184. copying build/lib.linux-x86_64-2.4/psutil/__init__.py -> /usr/lib64/python2./site-packages/psutil
  185. copying build/lib.linux-x86_64-2.4/psutil/_pslinux.py -> /usr/lib64/python2./site-packages/psutil
  186. copying build/lib.linux-x86_64-2.4/psutil/_psbsd.py -> /usr/lib64/python2./site-packages/psutil
  187. copying build/lib.linux-x86_64-2.4/psutil/_compat.py -> /usr/lib64/python2./site-packages/psutil
  188. copying build/lib.linux-x86_64-2.4/psutil/_pswindows.py -> /usr/lib64/python2./site-packages/psutil
  189. copying build/lib.linux-x86_64-2.4/psutil/_psposix.py -> /usr/lib64/python2./site-packages/psutil
  190. copying build/lib.linux-x86_64-2.4/psutil/_common.py -> /usr/lib64/python2./site-packages/psutil
  191. byte-compiling /usr/lib64/python2./site-packages/psutil/_psosx.py to _psosx.pyc
  192. byte-compiling /usr/lib64/python2./site-packages/psutil/_pssunos.py to _pssunos.pyc
  193. byte-compiling /usr/lib64/python2./site-packages/psutil/__init__.py to __init__.pyc
  194. byte-compiling /usr/lib64/python2./site-packages/psutil/_pslinux.py to _pslinux.pyc
  195. byte-compiling /usr/lib64/python2./site-packages/psutil/_psbsd.py to _psbsd.pyc
  196. byte-compiling /usr/lib64/python2./site-packages/psutil/_compat.py to _compat.pyc
  197. byte-compiling /usr/lib64/python2./site-packages/psutil/_pswindows.py to _pswindows.pyc
  198. byte-compiling /usr/lib64/python2./site-packages/psutil/_psposix.py to _psposix.pyc
  199. byte-compiling /usr/lib64/python2./site-packages/psutil/_common.py to _common.pyc
  200. [root@localhost psutil-2.0.]#
  201.  
  202. 进入python 试一下 psutil 模块是否安装正确
  203. #python
  204.  
  205. You are now leaving help and returning to the Python interpreter.
  206. If you want to ask for help on a particular object directly from the
  207. interpreter, you can type "help(object)". Executing "help('string')"
  208. has the same effect as typing a particular string at the help> prompt.
  209. >>> import psutil
  210. >>> psutil.cpu_times()
  211. scputimes(user=7924.96, nice=212.0, system=1933.8, idle=12099434.460000001, iowait=3665.8400000000001, irq=83.379999999999995, softirq=491.57999999999998, steal=0.0)
  212.  
  213. >>> psutil.swap_memory()
  214. sswap(total=8439095296L, used=921686016L, free=7517409280L, percent=10.9, sin=, sout=)
  215. >>> psutil.swap_memory().free
  216. 7517409280L
  217. >>>
  218.  
  219. 调用函数: 函数名.参数
  220.  
  221. 后面附函数&参数列表
  222.  
  223. 通过一个案例见证以下psutil 的功能
  224.  
  225. 以下通过shell &python实现一个服务器信息的简单监控,执行我做好的脚步
  226.  
  227. [root@localhost peter]# ./peter.sh
  228. 开机时间:-- ::
  229. 当前CPU使用率:1.9%
  230. 物理内存:7950M 使用率:10.6%
  231. Swap内存:8024M 使用率:10.9%
  232. 发送: Byte 发送包数:122654
  233. 接收: Byte 接收包数:46197965
  234. 盘符: /dev/sda3 挂载点: / 使用率: 29.6%
  235. 盘符: /dev/sda5 挂载点: /oracle 使用率: 29.6%
  236. 盘符: /dev/sda2 挂载点: /oracle/oradata 使用率: 42.8%
  237. 盘符: /dev/sda1 挂载点: /boot 使用率: 11.8%
  238. 盘符: /dev/sdb1 挂载点: /oracle/oradata2 使用率: 53.3%
  239. [root@localhost peter]#
  240.  
  241. 下面看一下peter.sh的内容内容,大家直接粘过去就能用。有兴趣的朋友可以自己再优化一下
  242.  
  243. #!/usr/bin/env python
  244. #coding:utf-
  245. import psutil
  246. import time
  247. import sys
  248. from optparse import OptionParser
  249. parser = OptionParser()
  250. parser.add_option("-t", "--time", dest="time",
  251. help="此参数可查看当前下载占的带宽,-t是测试时间", metavar="")
  252. parser.add_option("-d", "--deamon",action="store_false", dest="deamon", default=True,
  253. help="后台运行此脚本")
  254.  
  255. def Sysinfo():
  256. Boot_Start = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(psutil.boot_time()))
  257. time.sleep(0.5)
  258. Cpu_usage = psutil.cpu_percent()
  259. RAM = int(psutil.virtual_memory().total/(*))
  260. RAM_percent = psutil.virtual_memory().percent
  261. Swap = int(psutil.swap_memory().total/(*))
  262. Swap_percent = psutil.swap_memory().percent
  263. Net_sent = psutil.net_io_counters().bytes_sent
  264. Net_recv = psutil.net_io_counters().bytes_recv
  265. Net_spkg = psutil.net_io_counters().packets_sent
  266. Net_rpkg = psutil.net_io_counters().packets_recv
  267. BFH = r'%'
  268. print " \033[1;32m开机时间:%s\033[1;m" % Boot_Start
  269. print " \033[1;32m当前CPU使用率:%s%s\033[1;m" % (Cpu_usage,BFH)
  270. print " \033[1;32m物理内存:%dM\t使用率:%s%s\033[1;m" % (RAM,RAM_percent,BFH)
  271. print "\033[1;32mSwap内存:%dM\t使用率:%s%s\033[1;m" % (Swap,Swap_percent,BFH)
  272. print " \033[1;32m发送:%d Byte\t发送包数:%d个\033[1;m" % (Net_sent,Net_spkg)
  273. print " \033[1;32m接收:%d Byte\t接收包数:%d个\033[1;m" % (Net_recv,Net_rpkg)
  274.  
  275. for i in psutil.disk_partitions():
  276. print " \033[1;32m盘符: %s 挂载点: %s 使用率: %s%s\033[1;m" % (i[],i[],psutil.disk_usage(i[])[],BFH)
  277.  
  278. def Net_io(s):
  279. x =
  280. sum =
  281. while True:
  282. if x >= s:
  283. break
  284. r1 = psutil.net_io_counters().bytes_recv
  285. time.sleep()
  286. r2 = psutil.net_io_counters().bytes_recv
  287. y = r2 - r1
  288. print "%.2f Kb/s" % (y / 1024.0)
  289. sum += y
  290. x +=
  291. result = sum / x
  292. print "\033[1;32m%s秒内平均速度:%.2f Kb/s \033[1;m" % (x,result / 1024.0)
  293. if __name__ == "__main__":
  294. (options, args) = parser.parse_args()
  295. if options.time:
  296. Net_io(int(options.time))
  297. else:
  298. Sysinfo()
  299.  
  300. ######脚本至此结束
  301.  
  302. 附录1 psutil 模块的其它用法:
  303.  
  304. Example usages
  305. CPU
  306.  
  307. >>> import psutil
  308. >>> psutil.cpu_times()
  309. scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=, nice=0.0)
  310. >>>
  311. >>> for x in range():
  312. ... psutil.cpu_percent(interval=)
  313. ...
  314. 4.0
  315. 5.9
  316. 3.8
  317. >>>
  318. >>> for x in range():
  319. ... psutil.cpu_percent(interval=, percpu=True)
  320. ...
  321. [4.0, 6.9, 3.7, 9.2]
  322. [7.0, 8.5, 2.4, 2.1]
  323. [1.2, 9.0, 9.9, 7.2]
  324. >>>
  325. >>>
  326. >>> for x in range():
  327. ... psutil.cpu_times_percent(interval=, percpu=False)
  328. ...
  329. scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
  330. scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
  331. scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
  332. >>>
  333. >>> psutil.cpu_count()
  334.  
  335. >>> psutil.cpu_count(logical=False)
  336.  
  337. >>>
  338.  
  339. Memory
  340.  
  341. >>> psutil.virtual_memory()
  342. svmem(total=, available=, percent=75.1, used=, free=, active=, inactive=, buffers=, cached=)
  343. >>> psutil.swap_memory()
  344. sswap(total=, used=, free=, percent=14.1, sin=, sout=)
  345. >>>
  346.  
  347. Disks
  348.  
  349. >>> psutil.disk_partitions()
  350. [sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
  351. sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext, opts='rw')]
  352. >>>
  353. >>> psutil.disk_usage('/')
  354. sdiskusage(total=, used=, free=, percent=22.5)
  355. >>>
  356. >>> psutil.disk_io_counters(perdisk=False)
  357. sdiskio(read_count=, write_count=, read_bytes=, write_bytes=, read_time=, write_time=)
  358. >>>
  359.  
  360. Network
  361.  
  362. >>> psutil.net_io_counters(pernic=True)
  363. {'eth0': netio(bytes_sent=, bytes_recv=, packets_sent=, packets_recv=, errin=, errout=, dropin=, dropout=),
  364. 'lo': netio(bytes_sent=, bytes_recv=, packets_sent=, packets_recv=, errin=, errout=, dropin=, dropout=)}
  365. >>>
  366. >>> psutil.net_connections()
  367. [pconn(fd=, family=<AddressFamily.AF_INET: >, type=<SocketType.SOCK_STREAM: >, laddr=('10.0.0.1', ), raddr=('93.186.135.91', ), status='ESTABLISHED', pid=),
  368. pconn(fd=, family=<AddressFamily.AF_INET: >, type=<SocketType.SOCK_STREAM: >, laddr=('10.0.0.1', ), raddr=('72.14.234.100', ), status='CLOSING', pid=),
  369. pconn(fd=-, family=<AddressFamily.AF_INET: >, type=<SocketType.SOCK_STREAM: >, laddr=('10.0.0.1', ), raddr=('72.14.234.104', ), status='ESTABLISHED', pid=None),
  370. pconn(fd=-, family=<AddressFamily.AF_INET: >, type=<SocketType.SOCK_STREAM: >, laddr=('10.0.0.1', ), raddr=('72.14.234.83', ), status='SYN_SENT', pid=None)
  371. ...]
  372. >>>
  373. >>> psutil.net_if_addrs()
  374. {'lo': [snic(family=<AddressFamily.AF_INET: >, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
  375. snic(family=<AddressFamily.AF_INET6: >, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
  376. snic(family=<AddressFamily.AF_LINK: >, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
  377. 'wlan0': [snic(family=<AddressFamily.AF_INET: >, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
  378. snic(family=<AddressFamily.AF_INET6: >, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
  379. snic(family=<AddressFamily.AF_LINK: >, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
  380. >>>
  381. >>> psutil.net_if_stats()
  382. {'eth0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: >, speed=, mtu=),
  383. 'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: >, speed=, mtu=)}
  384.  
  385. Other system info
  386.  
  387. >>> psutil.users()
  388. [user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
  389. user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
  390. >>>
  391. >>> psutil.boot_time()
  392. 1365519115.0
  393. >>>
  394.  
  395. Process management
  396.  
  397. >>> import psutil
  398. >>> psutil.pids()
  399. [, , , , , , , , , , , , , , , ,
  400. , , , , , , , , , , ,
  401. , , , , , , , , , , ,
  402. , , , , , , , , , , ,
  403. , , , , , , , , , , ,
  404. , , , , , , , ]
  405. >>>
  406. >>> p = psutil.Process()
  407. >>> p.name()
  408. 'python'
  409. >>> p.exe()
  410. '/usr/bin/python'
  411. >>> p.cwd()
  412. '/home/giampaolo'
  413. >>> p.cmdline()
  414. ['/usr/bin/python', 'main.py']
  415. >>>
  416. >>> p.status()
  417. 'running'
  418. >>> p.username()
  419. 'giampaolo'
  420. >>> p.create_time()
  421. 1267551141.5019531
  422. >>> p.terminal()
  423. '/dev/pts/0'
  424. >>>
  425. >>> p.uids()
  426. puids(real=, effective=, saved=)
  427. >>> p.gids()
  428. pgids(real=, effective=, saved=)
  429. >>>
  430. >>> p.cpu_times()
  431. pcputimes(user=1.02, system=0.31)
  432. >>> p.cpu_percent(interval=1.0)
  433. 12.1
  434. >>> p.cpu_affinity()
  435. [, , , ]
  436. >>> p.cpu_affinity([]) # set
  437. >>>
  438. >>> p.memory_percent()
  439. 0.63423
  440. >>>
  441. >>> p.memory_info()
  442. pmem(rss=, vms=)
  443. >>> p.memory_info_ex()
  444. extmem(rss=, vms=, shared=, text=, lib=, data=, dirty=)
  445. >>> p.memory_maps()
  446. [pmmap_grouped(path='/lib/x86_64-linux-gnu/libutil-2.15.so', rss=, anonymous=, swap=),
  447. pmmap_grouped(path='/lib/x86_64-linux-gnu/libc-2.15.so', rss=, anonymous=, swap=),
  448. pmmap_grouped(path='/lib/x86_64-linux-gnu/libcrypto.so.1.0.0', rss=, anonymous=, swap=),
  449. pmmap_grouped(path='[heap]', rss=, anonymous=, swap=),
  450. pmmap_grouped(path='[stack]', rss=, anonymous=, swap=),
  451. ...]
  452. >>>
  453. >>> p.io_counters()
  454. pio(read_count=, write_count=, read_bytes=, write_bytes=)
  455. >>>
  456. >>> p.open_files()
  457. [popenfile(path='/home/giampaolo/svn/psutil/somefile', fd=)]
  458. >>>
  459. >>> p.connections()
  460. [pconn(fd=, family=<AddressFamily.AF_INET: >, type=<SocketType.SOCK_STREAM: >, laddr=('10.0.0.1', ), raddr=('93.186.135.91', ), status='ESTABLISHED'),
  461. pconn(fd=, family=<AddressFamily.AF_INET: >, type=<SocketType.SOCK_STREAM: >, laddr=('10.0.0.1', ), raddr=('72.14.234.100', ), status='CLOSING'),
  462. pconn(fd=, family=<AddressFamily.AF_INET: >, type=<SocketType.SOCK_STREAM: >, laddr=('10.0.0.1', ), raddr=('72.14.234.104', ), status='ESTABLISHED'),
  463. pconn(fd=, family=<AddressFamily.AF_INET: >, type=<SocketType.SOCK_STREAM: >, laddr=('10.0.0.1', ), raddr=('72.14.234.83', ), status='SYN_SENT')]
  464. >>>
  465. >>> p.num_threads()
  466.  
  467. >>> p.num_fds()
  468.  
  469. >>> p.threads()
  470. [pthread(id=, user_time=22.5, system_time=9.2891),
  471. pthread(id=, user_time=0.0, system_time=0.0),
  472. pthread(id=, user_time=0.0, system_time=0.0),
  473. pthread(id=, user_time=0.0707, system_time=1.1)]
  474. >>>
  475. >>> p.num_ctx_switches()
  476. pctxsw(voluntary=, involuntary=)
  477. >>>
  478. >>> p.nice()
  479.  
  480. >>> p.nice() # set
  481. >>>
  482. >>> p.ionice(psutil.IOPRIO_CLASS_IDLE) # IO priority (Win and Linux only)
  483. >>> p.ionice()
  484. pionice(ioclass=<IOPriority.IOPRIO_CLASS_IDLE: >, value=)
  485. >>>
  486. >>> p.rlimit(psutil.RLIMIT_NOFILE, (, )) # set resource limits (Linux only)
  487. >>> p.rlimit(psutil.RLIMIT_NOFILE)
  488. (, )
  489. >>>
  490. >>> p.suspend()
  491. >>> p.resume()
  492. >>>
  493. >>> p.terminate()
  494. >>> p.wait(timeout=)
  495.  
  496. >>>
  497. >>> psutil.test()
  498. USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND
  499. root 0.0 0.0 Jun17 : init
  500. root 0.0 0.0 Jun17 : kthreadd
  501. root 0.0 0.0 Jun17 : ksoftirqd/
  502. ...
  503. giampaolo 0.0 0.0 /dev/pts/ Jun19 : python2.
  504. giampaolo 0.0 2.2 : : chrome
  505. root 0.0 0.0 : : kworker/:
  506. >>>
  507.  
  508. Further process APIs
  509.  
  510. >>> for p in psutil.process_iter():
  511. ... print(p)
  512. ...
  513. psutil.Process(pid=, name='init')
  514. psutil.Process(pid=, name='kthreadd')
  515. psutil.Process(pid=, name='ksoftirqd/0')
  516. ...
  517. >>>
  518. >>> def on_terminate(proc):
  519. ... print("process {} terminated".format(proc))
  520. ...
  521. >>> # waits for multiple processes to terminate
  522. >>> gone, alive = psutil.wait_procs(procs_list, , callback=on_terminate)
  523. >>>
  524.  
  525. 附录2 各平台安装方法
  526.  
  527. Installing using pip on UNIX
  528.  
  529. The easiest way to install psutil on UNIX is by using pip (but first you might need to install python header files; see later). First install pip:
  530.  
  531. $ wget https://bootstrap.pypa.io/get-pip.py
  532. $ python get-pip.py
  533.  
  534. ...then run:
  535.  
  536. $ pip install psutil
  537.  
  538. You may need to install gcc and python header files first (see later).
  539. Installing on Windows
  540.  
  541. Just get the right installer for your Python version and architecture from: https://pypi.python.org/pypi/psutil/#downloadsSince wheels installers are also available you may also use pip.
  542. Compiling on Windows using Visual Studio
  543.  
  544. In order to compile psutil on Windows you'll need Visual Studio (Mingw32 is no longer supported). You must have the same version of Visual Studio used to compile your installation of Python, that is:
  545.  
  546. * Python 2.6: VS (download it from `here <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_)
  547. * Python 2.7: VS (download it from `here <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_)
  548. * Python 3.3, 3.4: VS (you can download it from `MS website <http://www.visualstudio.com/downloads/download-visual-studio-vs#d-2010-express>`_)
  549. * Python 3.5: `VS UP <http://www.visualstudio.com/en-au/news/vs2015-preview-vs>`_
  550.  
  551. ...then run:
  552.  
  553. setup.py build
  554.  
  555. ...or:
  556.  
  557. make.bat build
  558.  
  559. Compiling bit versions of Python 2.6 and 2.7 with VS requires Windows SDK and .NET Framework 3.5 SP1 to be installed first. Once you have those run vcvars64.bat, then compile: http://stackoverflow.com/questions/11072521/
  560. Installing on Linux
  561.  
  562. gcc is required and so the python headers. They can easily be installed by using the distro package manager. For example, on Debian and Ubuntu:
  563.  
  564. $ sudo apt-get install gcc python-dev
  565.  
  566. ...on Redhat and CentOS:
  567.  
  568. $ sudo yum install gcc python-devel
  569.  
  570. Once done, you can build/install psutil with:
  571.  
  572. $ python setup.py install
  573.  
  574. Installing on OS X
  575.  
  576. OS X installation from source will require gcc which you can obtain as part of the 'XcodeTools' installer from Apple. Then you can run the standard distutils commands. To build only:
  577.  
  578. $ python setup.py build
  579.  
  580. To install and build:
  581.  
  582. $ python setup.py install
  583.  
  584. Installing on FreeBSD
  585.  
  586. The same compiler used to install Python must be present on the system in order to build modules using distutils. Assuming it is installed, you can build using the standard distutils commands.
  587.  
  588. Build only:
  589.  
  590. $ python setup.py build
  591.  
  592. Install and build:
  593.  
  594. $ python setup.py install
  595.  
  596. Makefile
  597.  
  598. A makefile is available for both UNIX and Windows (make.bat). It provides some automations for the tasks described above and might be preferred over using setup.py. With it you can:
  599.  
  600. $ make install # just install (in --user mode)
  601. $ make uninstall # uninstall (needs pip)
  602. $ make test # run tests
  603. $ make clean # remove installation files

转自

Python实现linux自动化运维 (1) - CSDN博客 http://blog.csdn.net/lively1982/article/details/50053257

psutil监控CPU内存磁盘并告警 - CSDN博客 http://blog.csdn.net/lisheninasiainfo/article/details/54848054

python psutil监控系统资源【转】的更多相关文章

  1. 【321】python进程监控:psutil

    参考:Python进程监控-MyProcMonitor 参考:Python3.6 安装psutil 模块和功能简介 参考:psutil module (Download files) 参考:廖雪峰 - ...

  2. python系统监控及邮件发送

    python系统监控及邮件发送   #psutil模块是一个跨平台库,能轻松实现获取系统运行的进程和系统利用率   import psutil                              ...

  3. python多线程监控指定目录

    import win32file import tempfile import threading import win32con import os dirs=["C:\\WINDOWS\ ...

  4. python psutil简单示例

    python psutil简单示例 利用psutil编写简单的检测小脚本 0.安装psutil模块                                                    ...

  5. python性能监控初试

    标 题: python性能监控初试作 者: itdef链 接: http://www.cnblogs.com/itdef/p/3990765.html 欢迎转帖 请保持文本完整并注明出处 之前性能统计 ...

  6. 关于Linux_监控系统资源/性能命令_vmstat

    (系统资源查看命令-vmstat[监控系统资源命令])          command:vmstat  [刷新延时 刷新次数]   分解解析: procs:进程信息字段:              ...

  7. 教你用python爬虫监控教务系统,查成绩快人一步!

    教你用python爬虫监控教务系统,查成绩快人一步!这几天考了大大小小几门课,教务系统又没有成绩通知功能,为了急切想知道自己挂了多少门,于是我写下这个脚本. 设计思路:设计思路很简单,首先对已有的成绩 ...

  8. 自动化之路 python psutil模块 收集硬件信息

    一.psutil模块 1. psutil是一个跨平台库,能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等)信息.它主要应用于系统监控,分析和限制系统资源及进程的管理.它实现了 ...

  9. python - psutil 系统信息模块

    # .psutil是一个跨平台库能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等)信息. # 它主要用来做系统监控,性能分析,进程管理. # 它实现了同等命令行工具提供的功能 ...

随机推荐

  1. LeetCode 638 Shopping Offers

    题目链接: LeetCode 638 Shopping Offers 题解 dynamic programing 需要用到进制转换来表示状态,或者可以直接用一个vector来保存状态. 代码 1.未优 ...

  2. level3

    伸冤下:老师的评论是有看到!看完我就去修改程序了,忘记回复请原谅!= = 前阵子都在修改功能和思路,但是由于一个细节的错误找不到,导致没有成品可以上传...求谅解. 细心真的很重要 = =!!! im ...

  3. "Gun N' Rose" Team学习心得

    如果我比别人看得更远,只因为我站在巨人的肩膀上.                                                        ——牛顿 高级软件工程课程终于开课了!第 ...

  4. 在eclipse中编译调试ns3

    1首先把ns3项目导入eclipse 然后把上面的的ns3按照上面的提示即可导入成功.   然后可以运行一下 ./waf configure     2 配置C/C++ Build 右键工程,选择属性 ...

  5. OS X(10.10) python3.4 matplotlib的安装

    最近在用python做一些数据处理相关的工作,当然少不了matplotlib这个模块.之前在windows下分分钟安装成功,结果到了mac下死活编译不过去. 最后还是在stackoverflow上找到 ...

  6. 微信小程序简易table组件实现

    前提:微信小程序自1.6.3基础库版本库开始支持简洁组件,之前的版本因不支持,故在引用组件处默认为空节点.关于微信小程序已有模板为何还需构建组件?一是因为组件可以更方便的自定义并绑定行为,二是在其他页 ...

  7. Ubuntu17安装Jenkins

    Java安装 Jenkins基于Java, 所以需要先安装java. Linux下安装java只要配置java环境变量即可. 首先,解压java到相应目录,我一般习惯把安装的软件放到目录/usr/lo ...

  8. idea中 mybatis的debug文件需要放在src的目录下 不能加多余的路径

  9. 阿里Java编码规范

    详细,全面 很不错 阿里 Java编码规范

  10. pgm4

    这部分 cover 两个比较特殊的情形,一个是 Gaussian networks,一个是 exponential family. 正态分布常见的参数化策略是均值 和协方差矩阵 ,另一种是使用 inf ...