从零开始请看如下链接的前文提要部分 [http://www.zhaibibei.cn/python/linuxcpu/cpu-intro/](http://www.zhaibibei.cn/python/linuxcpu/cpu-intro/) --------- ##1. 开发环境 操作系统:CentOS 7.4 Python版本 :3.6 Django版本: 1.10.5 操作系统用户:oms 前面介绍了如何使用Python获取Linux/unix系统的CPU 内存数据 并将需要的系统信息放在了Django中 这里我们使用Djangp批量获取Linux性能数据 ---------- ## 2. 获取原理 我们通过paramiko模块来获取相关信息 关于redis存储,我们选择的value的数据类型为列表 **1. 新建redis表存放监控数据** 我们无需事先建立redis的key值 **2. 编写自定义命令获取性能数据并存入redis中** 如何创建自定义命令请参考 [http://www.zhaibibei.cn/oms/3.1/](http://www.zhaibibei.cn/oms/3.1/) ------ ##3. 程序解析 ###3.1 主体程序 这里我们用linuxperformance_redis.py程序来获取CPU 内存信息 改程序在每小时的0,15,30,45分别执行 ``` vim monitor/management/commands/linuxperformance_redis.py #coding=utf-8 from django.core.management.base import BaseCommand from monitor.models import linuxlist import os import redis import time from time import ctime,sleep import threading from monitor.command.getlinuxinfo import * class Command(BaseCommand): def handle(self, *args, **options): def getperformance(i): if i.monitor_type==1 and i.performance_type==1: ipaddress=i.ipaddress username=i.username password=i.password hostname1=i.hostname try: if i.os=='linux': ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=ipaddress,port=22,username=username,password=password) linuxcpu=getlinuxcpu(ssh) linuxmem=getlinuxmem(ssh) ssh.close() dskey='CPU='+ipaddress+'='+hostname1 value=nowtime+':'+ str(linuxcpu) if flag==1: value1=nnowtime+':'+ str(linuxcpu) r.lpush(dskey,value1) r.lpush(dskey,value) dskey='MEMORY='+ipaddress+'='+hostname1 value=nowtime+':'+ str(linuxmem) if flag==1: value1=nnowtime+':'+ str(linuxmem) r.lpush(dskey,value1) r.lpush(dskey,value) # print ipaddress+hostname1 else: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=ipaddress,port=22,username=username,password=password) unixcpu=getunixcpu(ssh) unixmem=getunixmem(ssh) ssh.close() dskey='CPU='+ipaddress+'='+hostname1 value=nowtime+':'+ str(unixcpu) if flag==1: value1=nnowtime+':'+ str(unixcpu) r.lpush(dskey,value1) r.lpush(dskey,value) dskey='MEMORY='+ipaddress+'='+hostname1 value=nowtime+':'+ str(unixmem) if flag==1: value1=nnowtime+':'+ str(unixmem) r.lpush(dskey,value1) r.lpush(dskey,value) except Exception as e: result1=str(e)+ipaddress mailcontent.append(result1) print (mailcontent) time.sleep(10) #print 'get linux performance' mailcontent=[] r=redis.StrictRedis() check_time=time.strftime('%Y%m%d%H %M', time.localtime()) if check_time.split()[1]=='00': flag=1 #flag used to determin when should push two times nowtime=str(time.mktime(time.strptime(check_time,'%Y%m%d%H %M'))).split('.')[0] nnowtime=str(int(str(time.mktime(time.strptime(check_time,'%Y%m%d%H %M'))).split('.')[0])-1) else: flag=0 nowtime=str(time.mktime(time.strptime(check_time,'%Y%m%d%H %M'))).split('.')[0] ip=linuxlist.objects.all().order_by('ipaddress') threads=[] for i in ip: t1 = threading.Thread(target=getperformance,args=(i,)) threads.append(t1) for t in threads: # t.setDaemon(True) t.start() t.join() #r.save() #print (mailcontent) ``` ### 3.2 调用的函数 上面主体程序调用了一些函数用于获取信息 文件路径为monitor/command/getlinuxinfo.py 这里选取几个,具体的参见我的github主页,可根据实际情况进行调整 获取Linux系统CPU信息 ``` def getlinuxcpu(ssh): result=[] stdin,stdout,stderr=ssh.exec_command('sar 2 3 |awk \'END {print 100-$NF}\'') err=stderr.readlines() if len(err) != 0: print (err) return False else: stdout_content=stdout.readlines() result= stdout_content if len(result) !=0: return round(float(result[0].strip()),2) else: print ('can not find linux sar command') ``` 获取Linux系统内存信息 ``` def getlinuxmem(ssh): result=[] stdin,stdout,stderr=ssh.exec_command('free -m |awk \' NR==2 {print (($3 - $6 - $7)/$2)*100}\'') err=stderr.readlines() if len(err) != 0: print (err) return False else: stdout_content=stdout.readlines() result= stdout_content if len(result) !=0: return round(float(result[0].strip()),2) else: print ('can not find linux free command') ``` 获取Unix系统CPU信息 ``` def getunixcpu(ssh): result=[] stdin,stdout,stderr=ssh.exec_command('sar 1 3 |awk \'END {print 100-$NF }\'') err=stderr.readlines() if len(err) != 0: print (err) return False else: stdout_content=stdout.readlines() result= stdout_content if len(result) !=0: return round(float(result[0].strip()),2) else: print ('can not find unix sar command') ``` 这个程序讲解如下: 1. 首先从linuxlist表中获取信息 2. 遍历每个数据库,当monitor_type为1和performance_type为1时继续 3. 利用取出来的信息连接Linux/Unix,当连接成功后根据系统类型选择相应的函数来获取CPU内存信息 4. 接下来使用redis的push功能保存数据 为方便后面处理数据,如果时间点为整点时,则保留2条信息,如当前时间为2017-12-12-0:00则会在2017-12-11-23:59保存一条相同数据 ### 3.3 一些注意事项 - 采用Python的多线程同时获取多个系统的信息 - 关于保存的时间采用绝对时间,并且整点会保存2次 - flag用来决定该时间段是否为整点 - 这里调用了send_mail函数用于程序运行异常时通知我 ------ ##4. 最终结果 使用如下命令运行 ``` /usr/bin/python /home/oms/mysite/manage.py linuxperformance_redis ``` [image:159 size:orig] [image:160 size:orig] [image:161 size:orig] 可以看出数据库的信息已经保存在redis数据库中了 ----- ##5. 设置自动运行 这里我们设置每十五分钟运行一次,并重定向所有日志至一个文件 这样我们可以通过检查该日志文件判断脚本是否正常运行 ``` 0,15,30,45 * * * * /usr/bin/python /home/oms/mysite/manage.py linuxperformance_redis >>/home/oms/mysite/crontab.log 2>&1 ``` -------- ## 5.源代码位置 欢迎访问我的github主页查看源码 https://github.com/bsbforever/oms_django 好了,这节介绍了如何利用自定义命令获取LInux/Unix服务器的信息并保存在redis数据库中 下节介绍如何将这些数据展示在一个页面上