答冷眼看世界
linux运维中通常喜欢使用shell脚本,但shell脚本是一步步执行结果,没有对整个代码的预判,对于中间运行出错后很难处理。所以python就闯入运维人员的眼中。
python中有很多module对于运维人员很友好的。
最基本的有os模块,无论是监控cpu使用情况:
#!/magedu/bin/python
import os
def getAllitems(host, oid):
sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid + '|grep Raw|grep Cpu|grep -v Kernel').read().split('\n')[:-1]
return sn1
def getDate(host):
items = getAllitems(host, '.1.3.6.1.4.1.2021.11')
date = []
rate = []
cpu_total = 0
#us = us+ni, sy = sy + irq + sirq
for item in items:
float_item = float(item.split(' ')[3])
cpu_total += float_item
if item == items[0]:
date.append(float(item.split(' ')[3]) + float(items[1].split(' ')[3]))
elif item == item[2]:
date.append(float(item.split(' ')[3] + items[5].split(' ')[3] + items[6].split(' ')[3]))
else:
date.append(float_item)
#calculate cpu usage percentage
for item in date:
rate.append((item/cpu_total)*100)
mean = ['%us','%ni','%sy','%id','%wa','%cpu_irq','%cpu_sIRQ']
#calculate cpu usage percentage
result = map(None,rate,mean)
return result
代码来源:https://zhuanlan.zhihu.com/p/27903397
还是网卡流量监测:
#!/magedu/bin/python
import re
import os
#get SNMP-MIB2 of the devices
def getAllitems(host,oid):
sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('\n')[:-1]
return sn1
#get network device
def getDevices(host):
device_mib = getAllitems(host,'RFC1213-MIB::ifDescr')
device_list = []
for item in device_mib:
if re.search('eth',item):
device_list.append(item.split(':')[3].strip())
return device_list
#get network date
def getDate(host,oid):
date_mib = getAllitems(host,oid)[1:]
date = []
for item in date_mib:
byte = float(item.split(':')[3].strip())
date.append(str(round(byte/1024,2)) + ' KB')
return date
链接:https://zhuanlan.zhihu.com/p/27903397
另外还有内存占用情况,文件目录的查找新建删除操作都是os模块的用武之地。
另外就是urllib、urllib2模块,对于判断网页请求响应、抓取web页面都是必会的。
至于更多的使用模块还有time、random、sys、numpy等。
以上只是针对运维中的问题列举了常用的模块,
如果楼主想系统学习Python的话,还建议买一本好的教材,一边读一边写代码,这样才能稳步提高编程能力。