q66262 发表于 2018-8-10 07:33:25

Python自动化运维

psutil库
  获取系统运行的进程和系统利用率

  # yum -y install python2
  # yum -y install python2-psutil
  # python

  1.cpu信息


[*]user 执行用户进程的时间百分比
[*]system 执行内核进程和中断的时间百分比
[*]idle cpu处于idle状态的时间百分比
[*]  iowait 由于IO等待而使CPU处于idle(空闲)状态的时间百分比

  >> import psutil
  >> psutil.cpu_times() #使用cpu_times()方法获取cpu的完整信息
  >> psutil.cpu_times(percpu=True) #显示所有逻辑cpu信息
  >> psutil.cpu_times().user#用户user的cpu时间比
  >> psutil.cpu_count()       #获取cpu的逻辑个数,默认logical=True4
  >> psutil.cpu_count(logical=False)#获取cpu的物理个数


  2.获取内存信息
  total(内存总数)、used(已使用的内存数)、free(空闲内存数)、buffers(缓冲使用数)、cache(缓存使用数)、swap(交换分区使用数)
  

>>> mem = psutil.virtual_memory()  
>>> mem
  
>>> mem.total
  
>>> mem.free
  
>>> mem.used
  
>>> psutil.swap_memory()
  

  3.磁盘信息
  read_count(读IO数)、write_count(写IO数)、read_bytes(IO读字节数)、write_bytes(IO写字节数)、read_time(磁盘读时间)、write_time(磁盘写时间)
  

>>> psutil.disk_partitions() #获取完整信息  
>>> psutil.disk_usage('/')   #获取分区的使用情况
  
>>> psutil.disk_io_counters()#获取硬盘总的IO个数、读写信息
  
>>> psutil.disk_io_counters(perdisk=True) #获取单个分区IO个数、读写信息
  

  4.网络信息
  bytes_sent(发送字节数)、 bytes_recv(接收字节数), packets_sent(发送数据包数), packets_recv(接收数据包数)
  

>>> psutil.net_io_counters() #获取网络总的IO信息,默认pernic=False  
>>> psutil.net_io_counters(pernic=True) #pernic=True 输出每个网络借口的IO信息
  

  5.其他系统信息
  psutil模块支持获取用户登录、开机时间等信息
  

>>> psutil.users() #返回当前登录系统的用户信息  
>>> import psutil,datetime
  
>>> psutil.boot_time() #获取开机时间,以linux时间戳格式返回
  
>>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") #转换成自然时间格式
  

系统进程管理方法
  

>>> import psutil  
>>> psutil.pids()#列出所有进程PID
  
>>> p = psutil.Process(1555)#实例化一个Process对象,参数为一进程PID
  
>>> p.name()#进程名
  
'sshd'
  
>>> p.exe()#进程bin路径
  
'/usr/sbin/sshd'
  
>>> p.cwd()#进程工作目录绝对路径
  
>>> p.status()#进程状态
  
'sleeping'
  
>>> p.create_time()#进程创建时间,时间戳格式
  
>>> p.uids()#进程uid信息
  
>>> p.gids()#进程gid信息
  
>>> p.cpu_times()#进程CPU时间信息,包括user、system的cpu时间
  
>>> p.cpu_affinity()#get进程CPU素和度,如果设置进程CPU素和度,将CPU号作为参数即可
  
>>> p.memory_info()#进程内存rss、vms信息
  
>>> p.memory_percent()#进程内存利用率
  
>>> p.connections()#返回打开进程socket的namedutples列表、包括fd、family、laddr等信息
  
>>> p.num_threads()#进程开启的线程数
  

popen类的使用
  

>>> import psutil  
>>> from subprocess import PIPE#通过psutil的Popen方法启动的应用程序,可以跟踪该程序运行的所有相关信息
  
>>> p = psutil.Popen(["/usr/bin/python","-c","print('hello')"],stdout=PIPE)
  
>>> p.name()
  
'python'
  
>>> p.username()
  
'root'
  
>>> p.communicate()
  
('hello\n', None)
  
>>> p.cpu_times()#得到进程运行的CPU时间
  

IP地址处理模块IPy

  # yum -y install python-IPy

  1.IP地址、网段的基本处理
  

>>> from IPy import IP  
>>> IP('10.0.0.0/8').version() #区分IPv4与IPv6
  
>>> IP('::1').version()
  
>>> ip = IP('192.168.0.0/16')
  
>>> print ip.len() #输出IP/16网段的IP个数
  
>>> for x in ip:   #输出IP清单
  
>>>   print(x)
  

  2.反向解析名称、IP类型、IP转换
  

>>> from IPy import IP  
>>> ip = IP('192.168.1.101')
  
>>> ip.reverseName()#反向解析地址格式
  
>>> ip.iptype()#为私网类型'PRIVATE'
  
>>> IP('8.8.8.8').iptype()#为公网类型 'PUBLIC'
  
>>> IP('8.8.8.8').int() #转换成整型格式
  
>>> IP('8.8.8.8').strHex() #转换成十六进制格式
  
>>> IP('8.8.8.8').strBin()#转换成二进制格式
  
>>> print(IP(0x8080808))#十六进制转成IP格式
  

  3.IP与掩码产生网段格式
  

>>> print(IP('192.168.1.0').make_net('255.255.255.0'))  
>>> print (IP('192.168.1.0/255.255.255.0',make_net=True))
  
>>> print (IP('192.168.1.0-192.168.1.255',make_net=True))
  

  结果都是:192.168.1.0/24
  4.也可以通过strNormal方法指定不同wantprefixlen参数值以定制不同输出类型的网段。
  wantprefixlen的取值及含义:


[*]wantprefixlen = 0无返回值
[*]wantprefixlen = 1prefix格式
[*]wantprefixlen = 2decimalnetmask格式
[*]wantprefixlen = 3lastIP格式
  操作如下:
  

>>> IP('192.168.1.0/24').strNormal(0)  '192.168.1.0'
  
>>> IP('192.168.1.0/24').strNormal(1)
  '192.168.1.0/24'
  
>>> IP('192.168.1.0/24').strNormal(2)
  '192.168.1.0/255.255.255.0'
  
>>> IP('192.168.1.0/24').strNormal(3)
  '192.168.1.0-192.168.1.255'
  

  5.判断IP地址和网段是否包含于于另一个网段中
  

>>> '192.168.1.100' in IP('192.168.1.0/24')  
>>> IP('192.168.1.0/24') in IP('192.168.0.0/16')
  

  判断两个网段是否存在重叠,采用IPy提供的overlaps方法
  

>>> IP('192.168.0.0/23').overlaps('192.168.1.0/24') #返回1代表存在重叠  
>>> IP('192.168.0.0/24').overlaps('192.168.2.0') #返回0代表不存在重叠
  

  示例 根据输入的IP或子网返回网络、掩码、广播、反向解析、子网数、IP类型等
  

#!/usr/bin/env python  
from IPy import IP
  

  
ip_s = raw_input('Please input an IP or net-range: ') #输入IP地址或网段地址
  
ips = IP(ip_s)
  
if len(ips) > 1: #为一个网络地址
  print ('net: %s' %ips.netmask()) #输出网络地址
  print ('netmask: %s' %ips.netmask()) #输出网络掩码地址
  print ('broadcast: %s' %ips.broadcast()) #输出网络广播地址
  print ('reverse address: %s' %ips.reverseNames()) #输出地址反向解析
  print ('subnet: %s' %len(ips))#输出网络子网数
  
else:
  print ('reverse address: %s' %ips.reverseNames()) #输出IP反向解析
  

  
print ('hexadecimal: %s' %ips.strHex()) #输出十六进制地址
  
print ('binary ip: %s' %ips.strBin()) #输出二进制地址
  
print ('iptype: %s' %ips.iptype()) #输出地址类型
  

  # vi ip_mask.py


DNS处理模块dnspython
  A记录:将主机名转换成IP地址
  MX记录:邮件交换记录,定义邮件服务器的域名
  CNAME记录:指别名记录,实现域名间的映射
  NS记录:标记区域的域名服务器及授权子域
  PTR记录:反向解析,于A记录相反,将IP转换成主机名
  SOA记录:SOA标记,一个起始授权区的定义

  # wget http://www.dnspython.org/kits/1.9.4/dnspython-1.9.4.tar.gz
  # tar -zxvf dnspython-1.9.4.tar.gz
  # python setup.py install

  实现A记录查询方法
  

#! /usr/bin/env python  
import dns.resolver
  

  
domain = raw_input('Please input an domain: ') #输入域名地址 如www.baidu.com
  
A = dns.resolver.query(domain,'A') #指定查询类型为A记录
  
for i in A.response.answer:#通过response.answer方法获取查询回应信息
  for j in i.items:    #遍历回应信息
  print j.address
  

  # python dns_simple.py
  Please input an domain: www.baidu.com

  实现MX记录查询方法
  

#! /usr/bin/env python  
import dns.resolver
  

  
domain = raw_input('Please input an domain: ') #如 163.com
  
MX = dns.resolver.query(domain,'MX')
  
for i in MX:
  print 'MX preference = ', i.preference,'mail exchanger = ',i.exchange
  

  实现NS记录查询方法
  

#!/usr/bin/env python  
import dns.resolver
  

  
domain = raw_input('Please input an domain: ') #输入一级域名如baidu.com
  
ns = dns.resolver.query(domain, 'NS')
  
for i in ns.response.answer:
  for j in i.items:
  print j.to_text()
  

  实现CNAME记录查询方法
  

#!/usr/bin/env python  
import dns.resolver
  

  
domain = raw_input('Please input an domain: ')
  
cname = dns.resolver.query(domain, 'CNAME') #指定查询类型为CNAME记录
  
for i in cname.response.answer: #结果将回应cname后的目标域名
  for j in i.items:
  print j.to_text()
  

  监控所有服务的IP是否正常
  

#!/usr/bin/python  
import dns.resolver
  
import os
  
import httplib
  

  
iplist=[]#定义域名IP列表变量
  
appdomain="www.taobao.com"#定义业务域名
  

  
def get_iplist(domain=""): #域名解析函数,解析成功IP将被追加到iplist
  try:
  A = dns.resolver.query(domain,'A') #解析A记录类型
  except Exception,e:
  print "dns resolver error:"+ str(e)
  return
  for i in A.response.answer:
  for j in i.items:
  iplist.append(j.address) #追加到iplist
  return True
  

  
def checkip(ip):
  checkurl=ip+":80"
  getcontent=""
  httplib.socket.setdefaulttimeout(5) #定义http连接超时时间(5秒)
  conn=httplib.HTTPConnection(checkurl) #创建http连接对象
  

  try:
  conn.request("GET","/",headers = {"Host": appdomain}) #发起URL请求,添加host主机头
  r=conn.getresponse()
  getcontent = r.read(15) #获取URL页面前15个字符,以便做可用性校验
  finally:
  if getcontent == "<!doctype html>": #监控URL页的内容一般是事先定义好的,比如"HTTP200"等
  print ip+" "
  else:
  print ip+" "
  

  
if __name__=="__main__":
  if get_iplist(appdomain) and len(iplist)>0:
  for ip in iplist:
  checkip(ip)
  else:
  print "DNS resolver error."
页: [1]
查看完整版本: Python自动化运维