python中系統資訊擷取psutil使用
#!/usr/bin/env python#coding:utf-8import psutilimport timeimport sysfrom optparse import OptionParserparser = OptionParser() parser.add_option("-t", "--time", dest="time", help="此參數可查看當前下載占的頻寬,-t是測試時間", metavar="10") parser.add_option("-d", "--deamon",action="store_false", dest="deamon", default=True, help="後台運行此指令碼") def Sysinfo(): Boot_Start = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(psutil.boot_time())) time.sleep(0.5) Cpu_usage = psutil.cpu_percent() RAM = int(psutil.virtual_memory().total/(1027*1024)) RAM_percent = psutil.virtual_memory().percent Swap = int(psutil.swap_memory().total/(1027*1024)) Swap_percent = psutil.swap_memory().percent Net_sent = psutil.net_io_counters().bytes_sent Net_recv = psutil.net_io_counters().bytes_recv Net_spkg = psutil.net_io_counters().packets_sent Net_rpkg = psutil.net_io_counters().packets_recv BFH = r'%' print " \033[1;32m開機時間:%s\033[1;m" % Boot_Start print " \033[1;32m當前CPU使用率:%s%s\033[1;m" % (Cpu_usage,BFH) print " \033[1;32m實體記憶體:%dM\t使用率:%s%s\033[1;m" % (RAM,RAM_percent,BFH) print "\033[1;32mSwap記憶體:%dM\t使用率:%s%s\033[1;m" % (Swap,Swap_percent,BFH) print " \033[1;32m發送:%d Byte\t發送包數:%d個\033[1;m" % (Net_sent,Net_spkg) print " \033[1;32m接收:%d Byte\t接收包數:%d個\033[1;m" % (Net_recv,Net_rpkg) for i in psutil.disk_partitions(): print " \033[1;32m盤符: %s 掛載點: %s 使用率: %s%s\033[1;m" % (i[0],i[1],psutil.disk_usage(i[1])[3],BFH)def Net_io(s): x = 0 sum = 0 while True: if x >= s: break r1 = psutil.net_io_counters().bytes_recv time.sleep(1) r2 = psutil.net_io_counters().bytes_recv y = r2 - r1 print "%.2f Kb/s" % (y / 1024.0) sum += y x += 1 result = sum / x print "\033[1;32m%s秒內平均速度:%.2f Kb/s \033[1;m" % (x,result / 1024.0)if __name__ == "__main__": (options, args) = parser.parse_args() if options.time: Net_io(int(options.time)) else: Sysinfo()
運行結果:
開機時間:2015-04-24 08:39:45
當前CPU使用率:1.0%
實體記憶體:985M 使用率:26.5%
Swap記憶體:2073M 使用率:0.0%
發送:140263274 Byte 發送包數:213610個
接收:1522552624 Byte 接收包數:25313640個
盤符: /dev/mapper/centos-root 掛載點: / 使用率: 32.8
盤符: /dev/xvda1 掛載點: /boot 使用率: 19.2%
systeminfo.py -t 10使用:
1.18 Kb/s
0.98 Kb/s
1.11 Kb/s
0.94 Kb/s
0.89 Kb/s
0.92 Kb/s
1.29 Kb/s
1.24 Kb/s
1.21 Kb/s
0.73 Kb/s
10秒內平均速度:1.05 Kb/s