最近正在学习python脚本基础编程。随便写了一个简单服务器信息检测脚本。有不足之处还请大家多多批评指正。
termcolor这个模块需要单独安装,只能在python2.6上正常运行
#!/usr/bin/env python2.6
import os
import sys
import re
import termcolor
def cpu():
cpu=open('/proc/cpuinfo','r')
lines = cpu.readlines()
for line in lines:
model=re.match('model name.*$',line)
if type(model).__name__ != 'NoneType':
print " CPU Type :|%s" %(model.group().split(':')[1])
break
def mem():
mem=open('/proc/meminfo','r')
total = [re.match('MemTotal.*$',x) for x in mem]
for i in range(len(total)):
if type(total[i]).__name__ != 'NoneType':
K=float(total[i].group().split()[1])
G="%2.3f GB" %(K/1024**2)
if K<12000000:
print " MemTotal: |%-45s| %10s" %(G,termcolor.colored("ERROR",'red'))
else:
print " MemTotal: |%-45s| %10s" %(G,termcolor.colored("OK",'green'))
break
def ipaddress():
cmd='/sbin/ip addr show dev eth0 | grep "inet " |awk \'{print $2}\'| awk -F\/ \'{print $1}\''
ip=os.popen(cmd).readlines()
num=len(ip)
if num == 1:
print " eth0: |"+termcolor.colored(str(num)+" IP on eth0",'red')
elif num >=2:
print " eth0: |"+termcolor.colored(str(num)+" IP on eth0",'green')
for i in range(len(ip)):
cmd="ping -c 4 -i 0.5 -I %s 119.57.20.28" %(ip[i].strip())
ping=os.popen(cmd).readlines()
loss=[re.match('.*loss.*$',j) for j in ping]
for k in range(len(loss)):
if type(loss[k]).__name__ != 'NoneType':
if loss[k].group().split()[5] == '100%':
print " eth0: |%-45s| %10s" %(ip[i].strip(),termcolor.colored("ERROR",'red'))
else:
print " eth0: |%-45s| %10s" %(ip[i].strip(),termcolor.colored("OK",'green'))
def dns():
cmd='/usr/bin/dig www.linuxtone.org | sed -n \'/ANSWER SECTION/,/;;/p\'|grep -v ";;"'
dig=os.popen(cmd).readlines()
if len(dig) == 0:
print " DNS: |%-45s| %10s" %("DNS configuration",termcolor.colored("ERROR",'red'))
else:
print " DNS: |%-45s| %10s" %("DNS configuration",termcolor.colored("OK",'green'))
def gateway():
cmd='/sbin/route -n|sed -n \'2~1p\''
gate=os.popen(cmd).readlines()
print " Gateway: |Gateway configuration"
for i in range(len(gate)):
print gate[i],
cpu()
mem()
ipaddress()
dns()
gateway()
运行效果:
转载于:https://blog.51cto.com/mayulin/533809