Python实现linux自动化运维 (1)

27 篇文章 1 订阅
6 篇文章 0 订阅

    通过 运用 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

>>> import psutil
>>> psutil.cpu_times()
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)
>>>
>>> for x in range(3):
...     psutil.cpu_percent(interval=1)
...
4.0
5.9
3.8
>>>
>>> for x in range(3):
...     psutil.cpu_percent(interval=1, percpu=True)
...
[4.0, 6.9, 3.7, 9.2]
[7.0, 8.5, 2.4, 2.1]
[1.2, 9.0, 9.9, 7.2]
>>>
>>>
>>> for x in range(3):
...     psutil.cpu_times_percent(interval=1, percpu=False)
...
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)
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)
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)
>>>
>>> psutil.cpu_count()
4
>>> psutil.cpu_count(logical=False)
2
>>>

Memory

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

Disks

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

Network

>>> psutil.net_io_counters(pernic=True)
{'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0),
 'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)}
>>>
>>> psutil.net_connections()
[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),
 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),
 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),
 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)
 ...]
>>>
>>> psutil.net_if_addrs()
{'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
        snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
        snic(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
 'wlan0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
           snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
           snic(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
>>>
>>> psutil.net_if_stats()
{'eth0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500),
 'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=65536)}

Other system info

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

Process management

>>> import psutil
>>> psutil.pids()
[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224,
 268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355,
 2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245,
 4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358,
 4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235,
 5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
>>>
>>> p = psutil.Process(7055)
>>> p.name()
'python'
>>> p.exe()
'/usr/bin/python'
>>> p.cwd()
'/home/giampaolo'
>>> p.cmdline()
['/usr/bin/python', 'main.py']
>>>
>>> p.status()
'running'
>>> p.username()
'giampaolo'
>>> p.create_time()
1267551141.5019531
>>> p.terminal()
'/dev/pts/0'
>>>
>>> p.uids()
puids(real=1000, effective=1000, saved=1000)
>>> p.gids()
pgids(real=1000, effective=1000, saved=1000)
>>>
>>> p.cpu_times()
pcputimes(user=1.02, system=0.31)
>>> p.cpu_percent(interval=1.0)
12.1
>>> p.cpu_affinity()
[0, 1, 2, 3]
>>> p.cpu_affinity([0])  # set
>>>
>>> p.memory_percent()
0.63423
>>>
>>> p.memory_info()
pmem(rss=7471104, vms=68513792)
>>> p.memory_info_ex()
extmem(rss=9662464, vms=49192960, shared=3612672, text=2564096, lib=0, data=5754880, dirty=0)
>>> p.memory_maps()
[pmmap_grouped(path='/lib/x86_64-linux-gnu/libutil-2.15.so', rss=16384, anonymous=8192, swap=0),
 pmmap_grouped(path='/lib/x86_64-linux-gnu/libc-2.15.so', rss=6384, anonymous=15, swap=0),
 pmmap_grouped(path='/lib/x86_64-linux-gnu/libcrypto.so.1.0.0', rss=34124, anonymous=1245, swap=0),
 pmmap_grouped(path='[heap]', rss=54653, anonymous=8192, swap=0),
 pmmap_grouped(path='[stack]', rss=1542, anonymous=166, swap=0),
 ...]
>>>
>>> p.io_counters()
pio(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632)
>>>
>>> p.open_files()
[popenfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
>>>
>>> p.connections()
[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'),
 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'),
 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'),
 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')]
>>>
>>> p.num_threads()
4
>>> p.num_fds()
8
>>> p.threads()
[pthread(id=5234, user_time=22.5, system_time=9.2891),
 pthread(id=5235, user_time=0.0, system_time=0.0),
 pthread(id=5236, user_time=0.0, system_time=0.0),
 pthread(id=5237, user_time=0.0707, system_time=1.1)]
>>>
>>> p.num_ctx_switches()
pctxsw(voluntary=78, involuntary=19)
>>>
>>> p.nice()
0
>>> p.nice(10)  # set
>>>
>>> p.ionice(psutil.IOPRIO_CLASS_IDLE)  # IO priority (Win and Linux only)
>>> p.ionice()
pionice(ioclass=<IOPriority.IOPRIO_CLASS_IDLE: 3>, value=0)
>>>
>>> p.rlimit(psutil.RLIMIT_NOFILE, (5, 5))  # set resource limits (Linux only)
>>> p.rlimit(psutil.RLIMIT_NOFILE)
(5, 5)
>>>
>>> p.suspend()
>>> p.resume()
>>>
>>> p.terminate()
>>> p.wait(timeout=3)
0
>>>
>>> psutil.test()
USER         PID %CPU %MEM     VSZ     RSS TTY        START    TIME  COMMAND
root           1  0.0  0.0   24584    2240            Jun17   00:00  init
root           2  0.0  0.0       0       0            Jun17   00:00  kthreadd
root           3  0.0  0.0       0       0            Jun17   00:05  ksoftirqd/0
...
giampaolo  31475  0.0  0.0   20760    3024 /dev/pts/0 Jun19   00:00  python2.4
giampaolo  31721  0.0  2.2  773060  181896            00:04   10:30  chrome
root       31763  0.0  0.0       0       0            00:05   00:00  kworker/0:1
>>>

Further process APIs

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

附录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:

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

...then run:

$ 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:

* Python 2.6:  VS 2008 (download it from `here <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_)
* Python 2.7:  VS 2008 (download it from `here <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_)
* 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>`_)
* Python 3.5: `VS 2015 UP <http://www.visualstudio.com/en-au/news/vs2015-preview-vs>`_

...then run:

setup.py build

...or:

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:

$ sudo apt-get install gcc python-dev

...on Redhat and CentOS:

$ sudo yum install gcc python-devel

Once done, you can build/install psutil with:

$ 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:

$ python setup.py build

To install and build:

$ 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:

$ python setup.py build

Install and build:

$ 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:

$ make install    # just install (in --user mode)
$ make uninstall  # uninstall (needs pip)
$ make test       # run tests
$ make clean      # remove installation files



  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值