• 热门专题

python获取linux系统信息、性能阀值、短信网关发送的例子

作者:峰云  发布日期:2013-05-18 10:04:22
Tag标签:python  系统信息  性能阀值  短信网关  
  • 这是以前写过的监控平台所用的系统信息收集的模块~~~~


    大家可以当成模块引入到自己的脚本上。


    获取系统信息的模块
    利用psutil可以得到系统的各种性能指标


    #-*- encoding: utf-8 -*- 
    import psutil 
    class 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_process 
            func_list = [self.get_process_info] 
            self.get_sys_warn_info(func_list, 
                                   process=webserver_process, 
                                   connection=True) 
            """获取数据库进程"""
            from config import database_process 
            func_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_report 
        def 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_percent 
            import time 
            self.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_percent 
            self.mem = psutil.phymem_usage() 
            return [self.mem.percent, mem_warn_percent, "内存占用率"], 
        def get_sys_disks_info(self, path="/"): 
            """获取硬盘信息"""
            from config import disks_warn_percent 
            self.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]) 
                    pass
                except Exception, e: 
                    #print e 
                    #print "no such process" 
                    pass
                finally: 
                    if connection: 
                        #print p[0].name, "connection:" 
                        est, syn = self.get_process_connection(p[0]) 
                        self.est = est 
                        self.syn = syn 
                        from config import net_warn_established, net_warn_syn 
                        e = [est, net_warn_established, "已建立连接"] 
                        s = [syn, net_warn_syn, "半开通连接"] 
                        return e, s 
        def 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 = 0
            SYN_SENT = 0
            for children in process.get_children(): 
                try: 
                    for connection in children.get_connections(): 
                        if connection.remote_address: 
                            if connection.status == 'SYN_SENT': 
                                SYN_SENT += 1
                            else: 
                                ESTABLISHED += 1
                except Exception, e: 
                    pass
            return  ESTABLISHED, SYN_SENT 
        def 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_avg 
            self.neti_avg = neti_avg 
            self.neto_avg = neto_avg 
            o = [neto_avg, neto_warn_avg, "网络流出平均速度"] 
            i = [neti_avg, neti_warn_avg, "网络流入平均速度"] 
            return o, i 
        def __str__(self): 
            self.check_sys_status() 
            object_str = """ 
            Cpus核心数目: %d 
            CPU使用率: %.2f%% 
            内存总数: %sMb 
            内存使用率: %.2f%% 
            硬盘使用率: %.2f%% 
            启动时间: %s 
            系统进程数目: %d 
            网络流出平均速度: %.4fk/s 
            网络流入平均速度: %.4fk/s 
            webserver已建立连接数:%d 
            webserver半开通连接数:%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_str 
    if __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 = False
    sms_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 hashlib 
        m = hashlib.md5(string) 
        data["MD5String"] = m.hexdigest() 
        encode = "" 
        import urllib 
        for key in data: 
            val = str(data[key]) 
            formater = "%s" * 4
            string = formater % (urllib.quote(key), 
                                 "=", 
                                 urllib.quote(val), 
                                 "&") 
            encode += string 
        return encode[:-1] 
    def posttohost(data): 
        """提交短信到发送列队"""
        url = "http://sms.powereasy.net/MessageGate/Message.aspx"
        for num in data["sendNums"]: 
            data["SendNum"] = num 
            string = constructData(data) 
            import urllib2 
            req = urllib2.Request(url, string) 
            urllib2.urlopen(req) 
            import time 
            time.sleep(2) 
    def getTime(formater): 
        """组成短信要求的时间格式"""
        import time 
        timenow = time.time() 
        local = time.localtime(timenow) 
        return time.strftime(formater, local) 
    import config 
    data = {} 
    data["ID"] = getTime("%Y%m%d%H%M%S") 
    data["UserName"] = config.sms_userName 
    data["Md5key"] = config.sms_md5Key 
    data["Content"] = "" 
    data["SendTiming"] = config.sms_sendTiming 
    data["SendTime"] = config.sms_sendTime 
    data["sendNums"] = config.sms_sendNum

    网络的IO的模块

     

    #!/usr/bin/python 
    #coding=utf-8 
    from __future__ import division 
    import sys 
    import os 
    import time 
    import signal 
    netcmd = '/sbin/ifconfig eth0 | grep bytes'
    def getnetio(line): 
        s1 = line.find('RX bytes:') + 9
        e1 = line.find(' ', s1) 
        neti = line[s1:e1] 
        s2 = line.find('TX bytes:') + 9
        e2 = 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 = 60
        neti_list = [] 
        neto_list = [] 
        while (count > 0): 
            count -= 1
            time.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_start 
            neto_total = netio[1] - neto_start 
            sec_total = time_curr - time_start 
            neti_start = netio[0] 
            neto_start = netio[1] 
            time_start = time_curr 
            neti_avg = neti_total / sec_total / 1024
            neti_list.append(neti_avg) 
            neto_avg = neto_total / sec_total / 1024
            neto_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 li 
        neti_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]

     

About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规