前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[周末往期回顾]使用Django获取Linux性能数据并存放在redis中

[周末往期回顾]使用Django获取Linux性能数据并存放在redis中

作者头像
bsbforever
发布2020-08-19 14:59:56
1.2K0
发布2020-08-19 14:59:56
举报

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/

3. 程序解析

3.1 主体程序

这里我们用linuxperformance_redis.py程序来获取CPU 内存信息

改程序在每小时的0,15,30,45分别执行

代码语言:javascript
复制
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信息

代码语言:javascript
复制
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系统内存信息

代码语言:javascript
复制
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信息

代码语言:javascript
复制
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. 最终结果

使用如下命令运行

代码语言:javascript
复制
/usr/bin/python  /home/oms/mysite/manage.py linuxperformance_redis
1.png
1.png
2.png
2.png
3.png
3.png

可以看出数据库的信息已经保存在redis数据库中了

5. 设置自动运行

这里我们设置每十五分钟运行一次,并重定向所有日志至一个文件

这样我们可以通过检查该日志文件判断脚本是否正常运行

代码语言:javascript
复制
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数据库中

下节介绍如何将这些数据展示在一个页面上

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-08-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 宅必备 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 开发环境
  • 2. 获取原理
  • 3. 程序解析
    • 3.1 主体程序
      • 3.2 调用的函数
        • 3.3 一些注意事项
        • 4. 最终结果
        • 5. 设置自动运行
        • 5.源代码位置
        相关产品与服务
        云数据库 Redis
        腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档