这是以前写过的监控平台所用的系统信息收集的模块~~~~
大家可以当成模块引入到自己的脚本上。
获取系统信息的模块
利用psutil可以得到系统的各种性能指标
#-*- encoding: utf-8 -*-import psutilclass PSU(object):"""使用psutil检查服务器系统进程"""def __init__(self):"""初始化"""self.warning_report = ""def check_sys_status(self):"""获取CPU,内存,硬盘的信息"""func_list = [self.get_sys_cpu_info,self.get_sys_mem_info,self.get_sys_disks_info]self.get_sys_warn_info(func_list)"""获取web服务器进程"""from config import webserver_processfunc_list = [self.get_process_info]self.get_sys_warn_info(func_list,process=webserver_process,connection=True)"""获取数据库进程"""from config import database_processfunc_list = [self.get_process_info]self.get_sys_warn_info(func_list,process=database_process,connection=False)"""检查网络"""func_list = [self.get_net_io]self.get_sys_warn_info(func_list)return self.warning_reportdef get_sys_warn_info(self, func_list, **args):for func in func_list:#print func.__name__msg_list = func(**args)if msg_list:for msg in msg_list:'''判断报警信息'''sys_warn_msg_list = ['warn_condiction','warn_num','warn_msg']msg_dict = dict(zip(sys_warn_msg_list, msg))if msg_dict['warn_condiction'] > msg_dict['warn_num']:warn_msg = msg_dict['warn_msg']warn_num = str(msg_dict['warn_condiction'])self.warning_report += warn_msg + warn_num + '\n'def get_sys_cpu_info(self):"""获取CPU信息"""from config import cpu_warn_percentimport timeself.cpu_percent = psutil.cpu_percent(interval=0)time.sleep(1)self.cpu_percent = psutil.cpu_percent(interval=1)return [self.cpu_percent, cpu_warn_percent, "CPU占用率"],def get_sys_mem_info(self):"""获取MEM信息"""from config import mem_warn_percentself.mem = psutil.phymem_usage()return [self.mem.percent, mem_warn_percent, "内存占用率"],def get_sys_disks_info(self, path="/"):"""获取硬盘信息"""from config import disks_warn_percentself.disks = psutil.disk_usage(path)return [self.disks.percent, disks_warn_percent, "硬盘占用率"],def get_process_info(self, **args):process_name_list = args['process']connection = args['connection']"""获取特定进程的信息"""for process_name in process_name_list:p = self.get_process_by_name(process_name)try:self.get_process_io(p[0])passexcept Exception, e:#print e#print "no such process"passfinally:if connection:#print p[0].name, "connection:"est, syn = self.get_process_connection(p[0])self.est = estself.syn = synfrom config import net_warn_established, net_warn_syne = [est, net_warn_established, "已建立连接"]s = [syn, net_warn_syn, "半开通连接"]return e, sdef get_process_by_name(self, process_name):return [process for process in psutil.process_iter()if process_name in process.name and process.ppid == 1]def get_process_connection(self, process):"获取进程的连接数"ESTABLISHED = 0SYN_SENT = 0for children in process.get_children():try:for connection in children.get_connections():if connection.remote_address:if connection.status == 'SYN_SENT':SYN_SENT += 1else:ESTABLISHED += 1except Exception, e:passreturn ESTABLISHED, SYN_SENTdef get_process_io(self, process):"获取进程的I/O"return process.get_io_counters()def get_net_io(self):"""获取网络流量信息"""import netiostat(neti_list, neto_list, neti_avg, neto_avg) = netiostat.get_net_io()from config import neto_warn_avg, neti_warn_avgself.neti_avg = neti_avgself.neto_avg = neto_avgo = [neto_avg, neto_warn_avg, "网络流出平均速度"]i = [neti_avg, neti_warn_avg, "网络流入平均速度"]return o, idef __str__(self):self.check_sys_status()object_str = """Cpus核心数目: %dCPU使用率: %.2f%%内存总数: %sMb内存使用率: %.2f%%硬盘使用率: %.2f%%启动时间: %s系统进程数目: %d网络流出平均速度: %.4fk/s网络流入平均速度: %.4fk/swebserver已建立连接数:%dwebserver半开通连接数:%d""" % (psutil.NUM_CPUS, self.cpu_percent,psutil.TOTAL_PHYMEM / 1024 / 1024, self.mem.percent,self.disks.percent, psutil.BOOT_TIME / 60,len(psutil.get_pid_list()),self.neto_avg, self.neti_avg, self.est, self.syn)return object_strif __name__ == "__main__":p = PSU()print p
配置信息的一个例子
#-*- encoding: utf-8 -*-git_dir = "/tmp/gitpycheck" # 需要监控的文件夹的绝对路径smtp_addr = "" # smtp地址smtp_port = 587 # smtp端口smtp_account = "" # 账户smtp_password = "" # 密码mailList = [] # 收件列表mailSubject = "" # 邮件主题sms_notify = Falsesms_userName = ""sms_md5Key = ""sms_sendNum = []sms_sendTiming = 0 # 0为即时发送 1为定时发磅sms_sendTime = "" # 定时发送的时间cpu_warn_percent = 70 # cpu报警使用率mem_warn_percent = 90 # 内存报警使用率disks_warn_percent = 80 # 硬盘报警使用率neto_warn_avg = 2048.00 # 网络流出平均值neti_warn_avg = 1024.00 # 网络流入平均值net_warn_established = 200 # 已建立连接报警值net_warn_syn = 100 # 半开通连接报警值webserver_process = ['httpd'] # 需要监控的web服务器的进程名称database_process = ['mysql']
短信网关 可以利用短信推送信息
#-*- encoding: utf-8 -*-def constructData(data):"""根据规则组成md5"""data['Content'] = data['Content'].decode("utf-8")data['Content'] = data['Content'].encode("gb2312")string = "%s" * 7 % (data["ID"],data['UserName'],data['Md5key'],data['SendNum'],data['Content'],data['SendTiming'],data['SendTime'])import hashlibm = hashlib.md5(string)data["MD5String"] = m.hexdigest()encode = ""import urllibfor key in data:val = str(data[key])formater = "%s" * 4string = formater % (urllib.quote(key),"=",urllib.quote(val),"&")encode += stringreturn encode[:-1]def posttohost(data):"""提交短信到发送列队"""url = "http://sms.powereasy.net/MessageGate/Message.aspx"for num in data["sendNums"]:data["SendNum"] = numstring = constructData(data)import urllib2req = urllib2.Request(url, string)urllib2.urlopen(req)import timetime.sleep(2)def getTime(formater):"""组成短信要求的时间格式"""import timetimenow = time.time()local = time.localtime(timenow)return time.strftime(formater, local)import configdata = {}data["ID"] = getTime("%Y%m%d%H%M%S")data["UserName"] = config.sms_userNamedata["Md5key"] = config.sms_md5Keydata["Content"] = ""data["SendTiming"] = config.sms_sendTimingdata["SendTime"] = config.sms_sendTimedata["sendNums"] = config.sms_sendNum
网络的IO的模块
#!/usr/bin/python#coding=utf-8from __future__ import divisionimport sysimport osimport timeimport signalnetcmd = '/sbin/ifconfig eth0 | grep bytes'def getnetio(line):s1 = line.find('RX bytes:') + 9e1 = line.find(' ', s1)neti = line[s1:e1]s2 = line.find('TX bytes:') + 9e2 = line.find(' ', s2)neto = line[s2:e2]return (int(neti), int(neto))def int_handler(signum, frame):print ""sys.exit()def get_net_io():signal.signal(signal.SIGINT, int_handler)line = os.popen(netcmd).readline().strip()netio = getnetio(line)neti_start = netio[0]neto_start = netio[1]time_start = time.time()count = 60neti_list = []neto_list = []while (count > 0):count -= 1time.sleep(1)info = []line = os.popen(netcmd).readline().strip()netio = getnetio(line)info.append("网络流入总量:%.4fm, 网络流出总量:%.4fm"% (netio[0] / 1024 / 1024, netio[1] / 1024 / 1024))time_curr = time.time()neti_total = netio[0] - neti_startneto_total = netio[1] - neto_startsec_total = time_curr - time_startneti_start = netio[0]neto_start = netio[1]time_start = time_currneti_avg = neti_total / sec_total / 1024neti_list.append(neti_avg)neto_avg = neto_total / sec_total / 1024neto_list.append(neto_avg)info.append("当前网络流入速度:%.4fk/s"% (neti_total / sec_total / 1024))info.append("当前网络流出速度:%.4fk/s"% (neto_total / sec_total / 1024))info.append("当前网络平均流入速度:%.4fk/s"% (sum(neti_list) / len(neti_list)))info.append("当前网络平均流出速度:%.4fk/s"% (sum(neto_list) / len(neto_list)))#show = ", ".join(info)#sys.stdout.write(show+"\r")#sys.stdout.flush()#print ""def sort_avg(li):li.sort()li = li[1:-1]return lineti_list = sort_avg(neti_list)neto_list = sort_avg(neto_list)return (neti_list, neto_list, (sum(neti_list) / len(neti_list)),(sum(neto_list) / len(neto_list)))if __name__ == '__main__':print get_net_io()[3]