python自動化運維:系統基礎信息模塊


第一章:

首先介紹下系統性能信息模塊: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 apic/c++文件
你自己寫的一個程序編譯需要鏈接libpythonXX.(a|so)
(
:以上不含使用ctypes/ffi或者裸dlsym方式直接調用libpython.so)
其他正常使用python或者通過安裝源內的python類庫的不需要python-dev.



安裝后首先來看下它的功能:

1 獲取系統性能信息:

linux操作系統下CPU利用率有以下幾個部分:

usertime:執行用戶進程的時間百分比

system time:執行內核 進程和中斷時間百分比

Wait IO:由於IO等待而使CPU處於IDLE狀態的時間百分比

idleCPU處於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. 我們來看下Linuxfree命令得到的結果。單位是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=975056000python算出來的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():返回打開進程socketnamedtuples列表



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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM