您的位置:首页 > 编程语言 > Python开发

python自动化运维:系统基础信息模块

2017-07-30 14:34 656 查看
p { margin-bottom: 0.25cm; line-height: 120% } a:link { }

第一章:

首先介绍下系统性能信息模块:psutil

psutil能够轻松实现获取系统运行的进程和系统利用率包括CPU,内存,磁盘 和网络等。主要用于系统监控。对于系统维护来说是个不错的模块。首先我们来看下安装这个模块

使用如下的命令下载并安装:

wget https://pypi.Python.org/packages/source/p/psutil/psutil-2.1.3.tar.gz 
tar zxvf psutil-2.1.3.tar.gz
cd psutil-2.1.3/
python setup.py instal

提示如下错误:

psutil/_psutil_linux.c:12:20: fatal error: Python.h: 没有那个文件或目录
#include <Python.h>
^
compilation terminated.
error: command 'x86_64-Linux-gnu-gcc' failed with exit status 1

解决办法:
安装python的依赖包 python-dev
apt-get install python-dev



python-dev是干什么用的呢:

linux发行版通常会把类库的头文件和相关的pkg-config分拆成一个单独的xxx-dev(el)包.

以python为例, 以下情况是需要python-dev的

你需要自己安装一个源外的python类库, 而这个类库内含需要编译的调用python api的c/c++文件
你自己写的一个程序编译需要链接libpythonXX.(a|so)
(注:以上不含使用ctypes/ffi或者裸dlsym方式直接调用libpython.so)
其他正常使用python或者通过安装源内的python类库的不需要python-dev.



安装后首先来看下它的功能:

1 获取系统性能信息:

linux操作系统下CPU利用率有以下几个部分:

usertime:执行用户进程的时间百分比

system time:执行内核 进程和中断时间百分比

Wait IO:由于IO等待而使CPU处于IDLE状态的时间百分比

idle:CPU处于IDLE状态的时间百分比

首先介绍下用户时间,系统时间和始终时间的定义如下:

时钟时间(墙上时钟时间wall clock time):从进程从开始运行到结束,时钟走过的时间,这其中包含了进程在阻塞和等待状态的时间。
用户CPU时间:就是用户的进程获得了CPU资源以后,在用户态执行的时间。
系统CPU时间:用户进程获得了CPU资源以后,在内核态的执行时间。

  进程的三种状态为阻塞、就绪、运行。

   时钟时间 = 阻塞时间 + 就绪时间 +运行时间
   用户CPU时间 = 运行状态下用户空间的时间
   系统CPU时间 =  运行状态下系统空间的时间。

   用户CPU时间+系统CPU时间=运行时间。

我们来看下代码的实现:

import psutil



if __name__=="__main__":

print psutil.cpu_times()

print "user time is %s" % psutil.cpu_times().user

print "nice is %s" % psutil.cpu_times().nice

print "system is %s" % psutil.cpu_times().system

print "cpu count is %s" % psutil.cpu_count() #获取CPU的逻辑个数

print "cpu percent is %s" % psutil.cpu_percent()

运行结果如下:psutil.cpu_times()返回的是一个命名元组,可以用psutil.cpu_times().user的方式访问具体的元素

scputimes(user=938.3, nice=22.46, system=228.84, idle=9582.58, iowait=307.28, irq=0.0, softirq=5.26, steal=0.0, guest=0.0, guest_nice=0.0)

user time is 938.3

nice is 22.46

system is 228.84

cpu count is 2

cpu percent is 0.0



2 获取内存消息

采用psutil.virtual_memory() 得到如下信息:

1 total:内存总数

2 used:已使用的内存数

3 free:空闲的内存数

4 buffers: 缓冲使用数

5 cache:缓冲使用数

6 swap:交换分区使用数

具体每个字段的定义参见如下函数定义文档

Help on function virtual_memory in module psutil:

virtual_memory()

Return statistics about system memory usage as a namedtuple

including the following fields, expressed in bytes:

 

- total:

total physical memory available.

 

- available:

the actual amount of available memory that can be given

instantly to processes that request more memory in bytes; this

is calculated by summing different memory values depending on

the platform (e.g. free + buffers + cached on Linux) and it is

supposed to be used to monitor actual memory usage in a cross

platform fashion.

 

- percent:

the percentage usage calculated as (total - available) / total * 100

 

- used:

memory used, calculated differently depending on the platform and

designed for informational purposes only:

OSX: active + inactive + wired

BSD: active + wired + cached

LINUX: total - free

 

- free:

memory not being used at all (zeroed) that is readily available;

note that this doesn't reflect the actual memory available

(use 'available' instead)

 

Platform-specific fields:

 

- active (UNIX):

memory currently in use or very recently used, and so it is in RAM.

 

- inactive (UNIX):

memory that is marked as not used.

 

- buffers (BSD, Linux):

cache for things like file system metadata.

 

- cached (BSD, OSX):

cache for various things.

 

- wired (OSX, BSD):

memory that is marked to always stay in RAM. It is never moved to disk.

 

- shared (BSD):

memory that may be simultaneously accessed by multiple processes.

 

The sum of 'used' and 'available' does not necessarily equal total.

On Windows 'available' and 'free' are the same.



None

运行结果

svmem(total=2108862464L, available=924954624L, percent=56.1, used=1793261568L, free=315600896L, active=1393741824, inactive=284889088, buffers=39342080L, cached=570011648)

sswap(total=0L, used=0L, free=0L, percent=0.0, sin=0, sout=0)

[Finished in 0.4s]

我们以avaiable为例:单位是字节,值等于 linux中下面几个的相加和free + buffers + cached。在上面的结果中avaiable=924954624. 我们来看下Linux中free命令得到的结果。单位是KB

root@zhf-linux:/home/zhf/zhf/python_prj# free

total used free shared buff/cache available

Mem: 2059436 1084380 317076 47512 657980 681456

Swap: 0 0 0

free+buff+cache=317076+657980=975056KB=975056*1000=975056000和python算出来的924954624还是有些差距



3 获取磁盘信息

def get_harddisk():

print psutil.disk_partitions()

print psutil.disk_usage('/')

运行结果如下: disk_partitions包含了磁盘的分区以及挂载点。disk_usage返回的是磁盘的使用信息已经使用率。两个函数也都是返回的是命名元组

[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,relatime,errors=remount-ro,data=ordered')]

sdiskusage(total=243887898624L, used=9543921664L, free=221931511808L, percent=3.9)


4 网络信息:返回发送和接送的字节数,还包括错误的接收发送包。

def get_network_info():

print psutil.net_io_counters()

snetio(bytes_sent=1581480, bytes_recv=7878380, packets_sent=11354, packets_recv=16426, errin=0, errout=0, dropin=0, dropout=0)


5 其他系统信息:获取的是用户登陆的信息

def other_user_info():

print psutil.users()

[suser(name='zhf', terminal='tty7', host=':0', started=1501377810.0)]


6 系统进程:

psutil.pids()获取当前所有的进程pid。 这和shell 中ps -aux得到的结果是一样的

psutil.Process(PID) 通过传入具体的进程pid,可以得到这个进程对象。就可以得到这个进程的所有信息。

def get_process_id():

id_list=psutil.pids() #得到所有的进程PID,id_list是一个列表

for id in id_list:

p=psutil.Process(id) #得到每个进程PID对象

print "process name:%s,process path:%s,process state:%s,process create time:%s" % (p.name(),p.exe(),p.status(),p.create_time())

p.name:进程名

p.exe():进程bin路径

p.status():进程状态

p.create_time():进程创建时间

p.uids():进程UID信息

p.gids():进程GID

p.cpu_times():进程CPU信息

p.cpu_affinity():进程CPU亲和度

p.memory_info():进程内存利用率

p.io_counters():进程IO信息

p.connections():返回打开进程socket的namedtuples列表



IPY模块:

在网络规划中,经常有要计算大量的IP地址,包括网段,网络掩码,广播地址,子网数,IP类型等. IPY是这方面很强大的一个第三方模块。其中关于IP地址原理以及规划可以参考之前的另外一个帖子:http://www.cnblogs.com/zhanghongfeng/p/7142100.html


def ipy_function():

print IP('10.0.0.0/8').version() #得到IP地址的版本

print IP('::1').version()

ip=IP('191.168.0.0/28') #构造一个IP地址,其中网络地址为24位

print ip.len()

for x in ip:

print x #得到同一网段下的所有IP

运行结果; 网络长度为28,所以主机长度为4位,因此有15个地址

4

6

16

191.168.0.0

191.168.0.1

191.168.0.2

191.168.0.3

191.168.0.4

191.168.0.5

191.168.0.6

191.168.0.7

191.168.0.8

191.168.0.9

191.168.0.10

191.168.0.11

191.168.0.12

191.168.0.13

191.168.0.14

191.168.0.15


再来看另外一些功能

def ipy_function():

ip=IP('192.168.1.20')

print ip.reverseNames() #得到IP的方向解析地址

print ip.iptype() #IP网络类型

print ip.int() #换成整型格式

print ip.strHex() #16进制格式

print ip.strBin() #二进制格式

print ip.make_net('255.255.255.0') #生成网段格式

print IP('192.168.1.20/255.255.255.0',make_net=True) #生成网段格式

['20.1.168.192.in-addr.arpa.']

PRIVATE 私网地址

3232235796

0xc0a80114

11000000101010000000000100010100

192.168.1.0/24 网格地址

192.168.1.0/24


前面列举的都是一些基本功能,在实际工作中经常会遇到需要进行网络地址对比以及计算。我们来看下具体的实现。判断IP地址是否属于网段

print '192.168.1.100' in IP('192.168.1.0/24')


ip=IP('192.168.1.0/24')

print ip.net() #输出网络地址 192.168.1. 0

print ip.netmask() #输出掩码地址 255.255.255.0

print ip.broadcast() #输出广播地址 192.168.1.255



DNS模块:

我们在浏览器上上网的时候输入的是网站的域名,比如www.sina.com.cn。 但是在实际TCP/IP中,通信用的是IP地址寻址,因此需要将域名转换成底层可认识的IP地址。这就需要用到DNS查询。 我们来看下python中的dns模块用法

query模块中第一个参数为域名,第二个参数为类型,用来指定RR资源的类型:

A:将主机名换成IP地址

MX:邮件交换记录,定义邮件服务器的域名

CNAME:别名记录

NS:标记区域的域名服务器及授权子域

PTR:记录 与A记录相反,将IP转换成主机名


import dns.resolver

def dns_function():

a=dns.resolver.query('www.sina.com.cn','A')

for i in a.response.answer:

print i

print i.items

www.sina.com.cn. 46 IN A 117.34.15.57

[<DNS IN A rdata: 117.34.15.57>]



def dns_function():

a=dns.resolver.query('163.com','MX')

for i in a.response.answer:

print i

print i.items

163.com. 4887 IN MX 50 163mx00.mxmail.netease.com.

163.com. 4887 IN MX 10 163mx01.mxmail.netease.com.

163.com. 4887 IN MX 10 163mx02.mxmail.netease.com.

163.com. 4887 IN MX 10 163mx03.mxmail.netease.com.

[<DNS IN MX rdata: 50 163mx00.mxmail.netease.com.>, <DNS IN MX rdata: 10 163mx01.mxmail.neteas

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: