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

python自动化运维:系统基础信息模块的更多相关文章

  1. Python自动化运维 技术与最佳实践PDF高清完整版免费下载|百度云盘|Python基础教程免费电子书

    点击获取提取码:7bl4 一.内容简介 <python自动化运维:技术与最佳实践>一书在中国运维领域将有"划时代"的重要意义:一方面,这是国内第一本从纵.深和实践角度探 ...

  2. Python自动化运维:技术与最佳实践 PDF高清完整版|网盘下载内附地址提取码|

    内容简介: <Python自动化运维:技术与最佳实践>一书在中国运维领域将有“划时代”的重要意义:一方面,这是国内第一本从纵.深和实践角度探讨Python在运维领域应用的著作:一方面本书的 ...

  3. Day1 老男孩python自动化运维课程学习笔记

    2017年1月7日老男孩python自动化运维课程正式开课 第一天学习内容: 上午 1.python语言的基本介绍 python语言是一门解释型的语言,与1989年的圣诞节期间,吉多·范罗苏姆为了在阿 ...

  4. python自动化运维学习第一天--day1

    学习python自动化运维第一天自己总结的作业 所使用到知识:json模块,用于数据转化sys.exit 用于中断循环退出程序字符串格式化.format字典.文件打开读写with open(file, ...

  5. 【目录】Python自动化运维

    目录:Python自动化运维笔记 Python自动化运维 - day2 - 数据类型 Python自动化运维 - day3 - 函数part1 Python自动化运维 - day4 - 函数Part2 ...

  6. python自动化运维篇

    1-1 Python运维-课程简介及基础 1-2 Python运维-自动化运维脚本编写 2-1 Python自动化运维-Ansible教程-Ansible介绍 2-2 Python自动化运维-Ansi ...

  7. Python自动化运维的职业发展道路(暂定)

    Python职业发展之路 Python自动化运维工程 Python基础 Linux Shell Fabric Ansible Playbook Zabbix Saltstack Puppet Dock ...

  8. python自动化运维之CMDB篇-大米哥

    python自动化运维之CMDB篇 视频地址:复制这段内容后打开百度网盘手机App,操作更方便哦 链接:https://pan.baidu.com/s/1Oj_sglTi2P1CMjfMkYKwCQ  ...

  9. python自动化运维笔记1 —— 系统性能信息模块psutil

    一.系统基础信息模块 1.1 系统性能信息模块psutil psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率( ...

  10. python自动化运维之路~DAY5

    python自动化运维之路~DAY5 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.模块的分类 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数 ...

随机推荐

  1. 纯手工打造简单分布式爬虫(Python)

    前言 这次分享的文章是我<Python爬虫开发与项目实战>基础篇 第七章的内容,关于如何手工打造简单分布式爬虫 (如果大家对这本书感兴趣的话,可以看一下 试读样章),下面是文章的具体内容. ...

  2. ZooKeeper数据结构

    Time in ZooKeeper ZooKeeper跟踪时间的多种方式 1)Zxid:每个ZooKeeper状态变化将会接收到一个zxid(ZooKeeper Transaction Id)的时间戳 ...

  3. epclise设置tomcat方法(步骤)(菜鸟巧记二)

    epclise设置tomcat 1.打开epclise→window→preferences 2.输入server,打开server→runtime environments→选择add新建 3.打开 ...

  4. 通过bin-log对mysql进行数据恢复

    mysqlbinlog --database=数据库名 --start-date="2017-06-01 5:00:00"  --stop-date="2017-06-1 ...

  5. 题解 最优的挤奶方案(Optimal Milking)

    最优的挤奶方案(Optimal Milking) 时间限制: 1 Sec  内存限制: 128 MB 题目描述 农场主 John 将他的 K(1≤K≤30)个挤奶器运到牧场,在那里有 C(1≤C≤20 ...

  6. js中的数字格式变成货币类型的格式

    <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8& ...

  7. 【LeetCode】73. Set Matrix Zeroes

    题目: Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Fo ...

  8. CSS3学习系列之布局样式(二)

    使用盒布局 在CSS3中,通过box属性来使用盒布局,例子如下: <!DOCTYPE html> <html lang="en"> <head> ...

  9. Spring Boot简单xml配置集成mybatis

    一.xml配置版 1.properties文件中增加的配置: mybatis.config-locations=classpath:mybatis/mybatis-config.xml mybatis ...

  10. java 邮件发送工具类

    首先需要下载mail.jar文件,我个人通常是使用maven中心库的那个: <dependency> <groupId>javax.mail</groupId> & ...