您的位置:首页 > 运维架构 > Linux

[Python]—Linux Server 系统监控程序

2014-07-14 20:36 423 查看
学习python,写一个小程序加深对Linux和python的理解,程序功能不全,需要逐步完善。

主要功能:

1、获取Server Name

2、获取操作系统版本信息

3、获取CPU硬件信息、CPU的使用率

4、获取内存使用信息

5、获取相关网络信息

6、获取磁盘及分区的相关信息

7、获取Server所有的用户名

8、获取服务器开机时间、运行时间相关信息

9、获取运行队列负载信息

10、获取系统进程总数、占用CPU最大的进程、占用内存最大的进程

11、获取登陆用户的信息

12、解析命令行,将输出导入到文件中保存(重定向输出)

说明:需要自己安装一个psutil包,功能很强大,但是在在本程序中主要还是自己实现为主,仅仅用来获取了一个准确的CPU利用率。

文件名:ServerInfo.py 下载

#!/usr/bin/env python
#coding=utf-8

import os
import re
import socket
import fcntl
import struct
import platform
import sys
import getopt,pwd
import psutil   #需要自己安装
from collections import OrderedDict

def serverName():
"""
print the hostname information
"""
sys=os.name
if sys=='posix':
name=os.popen('hostname').read().split('\n')[0]
str="SERVER NAME"
print '%-15s: %s' %(str,name)
else:
return

def sysInfo():
"""
print the system platform information
"""
str='SYSTEM VERSION'
print '%-15s: %s' %(str,platform.platform().strip())

def cpu():
"""
print the cpu infomation
"""
cpu=open('/proc/cpuinfo','r')
lines=cpu.readlines()
for line in lines:
model=re.match("model name.*$",line)
cache=re.match("cache size.*$",line)
if type(model).__name__!='NoneType':
Str="CPU TYPE"
print "%-15s: %s" %(Str,model.group().split(":")[1].strip())
if type(cache).__name__!='NoneType':
Str="CPU CACHE"
print "%-15s: %s" %(Str,cache.group().split(":")[1].strip())
def get_cpu_percent(interval=1):
return psutil.cpu_percent(interval=1)
Str='CPU PERCENT'
print '%-15s: %s' %(Str,str(get_cpu_percent())+'%')

def mem():
"""
print the memory information
"""
meminfo=OrderedDict()
mem=open('/proc/meminfo','r')
lines=mem.readlines()
for line in lines:
meminfo[line.split(':')[0]]=line.split(":")[1].strip()
str='TOTAL MEMORY'
print "%-15s: %s" %(str,meminfo['MemTotal'])
str='FREE MEMORY'
print "%-15s: %s" %(str,meminfo['MemFree'])

def networkInfo():
"""
print the network information
"""
def get_ip_address(ifname):
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, #SIOCGIFADDR
struct.pack('256s',ifname[:15])
)[20:24])
interfaces=OrderedDict()
dict={}
f=os.popen("ifconfig | grep  'HWaddr' |grep -v '127.0.0.1' |awk '{print $1\",\"$NF}'")
for ifn in f.readlines():
ifname=ifn.split(",")[0].strip()
ifmac=ifn.split(",")[1].strip()
ipaddr=get_ip_address(ifname)
interfaces[ifname]=(ifmac,ipaddr)
for ifn in interfaces:
print "%-15s: MACaddr %s IPaddr %s" %(ifn.upper(),interfaces[ifn][0],interfaces[ifn][1])

def diskInfo():
"""
print the disk information
"""
def disk_fs_usage(path):
"""
return total/used/free space info for a filesystem
"""
fs=os.statvfs(path)  #https://docs.python.org/2/library/statvfs.html
total=fs.f_frsize*fs.f_blocks
free=fs.f_frsize*fs.f_bfree
used=fs.f_frsize*(fs.f_blocks-fs.f_bfree)
return {
'total':int(float(total)/1024/1024),
'used':int(float(used)/1024/1024),
'free':int(float(used)/1024/1024)}

f=open('/proc/mounts','r')
mounts=f.readlines()
fsInfo={}
for mount in mounts:
if mount.startswith('/dev/'):
mount=mount.split()
dev=mount[0]
target=mount[1]
usageDict=disk_fs_usage(target)
fsInfo[dev]=usageDict
#print
Str='DISK INFO(MB)'
fs1=list(fsInfo)[0]
print "%-15s: %s %s" %(Str,fs1,str(fsInfo[fs1]).strip('{}').replace("'","").replace(","," "))
for fs in list(fsInfo)[1:]:
print '%26s %s' %(fs,str(fsInfo[fs]).strip('{}').replace("'","").replace(","," "))

def runTime():
f=os.popen("date -d \"$(awk -F. '{print $1}' /proc/uptime) second ago\" +\"%Y-%m-%d %H:%M:%S\"")
starttime=''
duration=''
starttime=f.readline().strip()
f=os.popen("awk -F. '{days=$1/86400;hours=($1%86400)/3600;minutes=($1%3600)/60;seconds=$1%60;printf(\"%ddays,%dhours,%dminutes,%dseconds\",days,hours,minutes,seconds)}' /proc/uptime")
duration=f.readline().strip()
Str='START TIME'
print '%-15s: %s' %(Str,starttime)
Str='RUN TIME'
print '%-15s: %s' %(Str,duration)

def loadAverage():
"""
表示在过去的1、5、15分钟内运行队列中的平均进程数量
"""
f=os.popen("uptime | awk -F',' '{print $4$5$6}'")
line=f.readline().strip().split();
av1=line[2]
av5=line[3]
av15=line[4]
Str='LOAD AVERAGE'
print '%-15s: %s %s %s' %(Str,av1,av5,av15)

def processInfo():
pids=[]
def get_pids():
f=os.popen('ps aux| grep -v "%MEM"')
for p in f.readlines():
p=p.split()
pid=(p[0],p[1],p[2],p[3],p[-1][:15])
pids.append(pid)

get_pids()
def max_mem_proc():
return sorted(pids,key=lambda k: k[3]) #sort by memory
def max_cpu_proc():
return sorted(pids,key=lambda k: k[2]) #sort by cpu

max_cpu=max_cpu_proc()[-1]
max_mem=max_mem_proc()[-1]
Str='TOTAL PROCESSES'
print '%-15s: %s' %(Str,len(pids))
Str='MAX CPU PROCESS'
print '%-15s: USER:%s PID %s CPU:%s MEM:%s COMMAND:%s' \
%(Str,max_cpu[0],max_cpu[1],max_cpu[2],max_cpu[3],max_cpu[4])
Str='MAX MEM PROCESS'
print '%-15s: USER:%s PID %s CPU:%s MEM:%s COMMAND:%s' \
%(Str,max_mem[0],max_mem[1],max_mem[2],max_mem[3],max_mem[4])

def getusers():
users=pwd.getpwall()
#print
Str='ALL USERS'
count=0;
print '%-15s:' %Str,
for user in users:
print user.pw_name,
count+=1
if count%8==0:
print ''
print ' '*16,
print ''

def loggin():
f=os.popen("who |grep -v '(:0.*)'")
Str='LOGGIN USERS'
print '%-15s: %s' %(Str,f.readline().strip())
for line in f.readlines():
print ' '*16,
print line.strip()

class RD_OUTPUT:
def rd_output_begin(self,filename):
self.output=open(os.path.join(os.getcwd(),filename),'w')
sys.stdout=self.output

def rd_output_end(self):
sys.stdout=sys.__stdout__
self.output.close()

class cmd_line:
def __usage(self):
print 'usage:ServerInfo.py [-h] [-f]\n'
print 'Linux Server Usage Monitor'
print 'optional arguments:'
print '   -h --help     help information'
print '   -f --file=    outputfile'

def __init__(self):
try:
opts,args=getopt.getopt(sys.argv[1:],"hf:",["help","file="])
except getopt.GetoptError:
print 'Error:unrecognized arguments!'
print 'Please execute "ServerInfo.py --help" to get more information!'
self.__usage()
sys.exit()

self.filename="ServerInfo.txt"
for op,value in opts:
if op in ('-f','--file='):
self.filename=value
if op in ('-h','--help'):
self.__usage()
sys.exit()

if __name__=='__main__':
arguments=False
if len(sys.argv)>1:
arguments=True
if  arguments:
cmd=cmd_line()
out=RD_OUTPUT()
out.rd_output_begin(cmd.filename)

serverName()
runTime()
sysInfo()
cpu()
mem()
networkInfo()
diskInfo()
processInfo()
loadAverage()
getusers()
loggin()

if arguments:
out.rd_output_end()
执行结果:

1、输出到屏幕上:



2、输出到文件中:



相关博客:

load average 相关:http://www.51testing.com/html/85/132585-804084.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: