几个python scripts

统计CPU信息

#!/usr/bin/env Python

from __future__ import print_function

from collections import OrderedDict

import pprint

def cpuinfo():

”’ Return the information in /proc/cpuinfo

as a dictionary in the following format:

cpu_info[‘proc0’]={…}

cpu_info[‘proc1′]={…}

”’

cpuinfo=OrderedDict()

procinfo=OrderedDict()

nprocs = 0

with open(‘/proc/cpuinfo’) as f:

for line in f:

if not line.strip():

# end of one processor

cpuinfo[‘proc%s’ % nprocs] = procinfo

nprocs=nprocs+1

# Reset

procinfo=OrderedDict()

else:

if len(line.split(‘:’)) == 2:

procinfo[line.split(‘:’)[0].strip()] = line.split(‘:’)[1].strip()

else:

procinfo[line.split(‘:’)[0].strip()] = ”

return cpuinfo

if __name__==’__main__’:

cpuinfo = cpuinfo()

for processor in cpuinfo.keys():

print(cpuinfo[processor][‘model name’])

运行结果

[root@AMH python]# python cpu1.py

Intel(R) Core(TM) i3-4170 CPU @ 3.70GHz

统计CPU在15分钟内的负载

import os

def load_stat():

loadavg = {}

f = open(“/proc/loadavg”)

con = f.read().split()

f.close()

loadavg[‘lavg_1’]=con[0]

loadavg[‘lavg_5’]=con[1]

loadavg[‘lavg_15’]=con[2]

loadavg[‘nr’]=con[3]

loadavg[‘last_pid’]=con[4]

return loadavg

print “loadavg”,load_stat()[‘lavg_15’]

运行结果

[root@AMH python]# python cpu2.py

loadavg 0.00

统计内存使用情况

#!/usr/bin/env Python

from __future__ import print_function

from collections import OrderedDict

def meminfo():

”’ Return the information in /proc/meminfo

as a dictionary ”’

meminfo=OrderedDict()

with open(‘/proc/meminfo’) as f:

for line in f:

meminfo[line.split(‘:’)[0]] = line.split(‘:’)[1].strip()

return meminfo

if __name__==’__main__’:

#print(meminfo())

meminfo = meminfo()

print(‘Total memory: {0}’.format(meminfo[‘MemTotal’]))

print(‘Free memory: {0}’.format(meminfo[‘MemFree’]))

运行结果

[root@AMH python]# python mem.py

Total memory: 615036 kB

Free memory: 49288 kB

统计网络使用情况

#!/usr/bin/env Python

import time

import sys

if len(sys.argv) > 1:

INTERFACE = sys.argv[1]

else:

INTERFACE = ‘eth0’

STATS = []

print ‘Interface:’,INTERFACE

def rx():

ifstat = open(‘/proc/net/dev’).readlines()

for interface in ifstat:

if INTERFACE in interface:

stat = float(interface.split()[1])

STATS[0:] = [stat]

def tx():

ifstat = open(‘/proc/net/dev’).readlines()

for interface in ifstat:

if INTERFACE in interface:

stat = float(interface.split()[9])

STATS[1:] = [stat]

print ‘In Out’

rx()

tx()

while True:

time.sleep(1)

rxstat_o = list(STATS)

rx()

tx()

RX = float(STATS[0])

RX_O = rxstat_o[0]

TX = float(STATS[1])

TX_O = rxstat_o[1]

RX_RATE = round((RX – RX_O)/1024/1024,3)

TX_RATE = round((TX – TX_O)/1024/1024,3)

print RX_RATE ,’MB ‘,TX_RATE ,’MB’

运行结果

[root@AMH python]# python net.py

Interface: eth0

In Out

0.008 MB 0.002 MB

0.006 MB 0.001 MB

0.007 MB 0.002 MB

0.008 MB 0.002 MB

0.008 MB 0.002 MB

0.008 MB 0.002 MB

0.008 MB 0.002 MB

Leave a Reply