常用Python脚本
1.请按照这样的日期格式(xxxx-xx-xx)每日生成一个文件,例如今天生成的文件为2019-04-26.log, 并且把磁盘的使用情况写到到这个文件中。
import time, os new_time = time.strftime("%Y-%m-%d") disk_status = os.popen('df -h').readlines() #readlines f = open(new_time+'.log', 'w') f.write('%s\n' % disk_status) f.flush() f.close()
read 读取整个文件
readline 读取下一行
readlines 读取整个文件到一个迭代器以供我们遍历(读取到一个list中,以供使用,比较方便)、
2.统计出每个IP的访问量有多少?(从日志文件中查找)。
1 #!/usr/bin/env python 2 #!coding=utf-8 3 4 5 list = [] 6 f = open('/var/log/httpd/access_log', 'r') 7 star = f.readlines() 8 f.close() 9 for i in star: 10 ip = i.split()[0] 11 list.append(ip) 12 list_num = set(list) 13 for j in list_num: 14 num = list.count(j) 15 16 print('%s-%s' %(j, num))
3.查看网段里有多少ip地址
import IPy ip = IPy.IP('172.27.40.0/26') for i in ip: print(i) print(ip.len()) 首先下载IPy库 python3 -m pip install --upgrade pip 升级pip pip3 install IPy
4.Python监控CPU情况
1、实现原理:通过SNMP协议获取系统信息,再进行相应的计算和格式化,最后输出结果
2、特别注意:被监控的机器上需要支持snmp。yum install -y net-snmp*安装
import os def getAllitems(host): sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + '.1.3.6.1.4.1.2021.11' + '|grep Raw|grep Cpu|grep -v Kernel').read().split( '\n')[:-1] return sn1 def getDate(host): items = getAllitems(host) 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 args = [rate, mean] result = list(map(list, zip(*args))) #map()函数 是内置的函数,在Python2中返回的是列表,在Python3中返回的是迭代器。需要转换成列表形式,想要了解更多的map()运用在我的内置函数里面 return result if __name__ == '__main__': hosts = ['127.0.0.1'] for host in hosts: print('==========' + host + '==========') result = getDate(host) print('Cpu(s)'), print(result) for i in range(7): print(' %s.f%s' % (result[i][0], result[i][1]))
结果:
==========127.0.0.1========== Cpu(s) [[0.6313887286225928, '%us'], [0.0, '%ni'], [1.4108272280946212, '%sy'], [93.4923416901623, '%id'], [4.45129053678928, '%wa'], [0.0, '%cpu_irq'], [0.014151816331196046, '%cpu_sIRQ']] 0.6313887286225928.f%us 0.0.f%ni 1.4108272280946212.f%sy 93.4923416901623.f%id 4.45129053678928.f%wa 0.0.f%cpu_irq 0.014151816331196046.f%cpu_sIRQ