python實現監控信息收集

監控信息腳本使用了psutil、schedule,廢話不多說直接上代碼

考慮到監控信息的數據並不需要持久化,於是選擇把監控數據存入到redis中,從redis中讀取監控數據進行web展示即可

 

  1 import psutil
  2 import socket
  3 import redis
  4 import schedule
  5 import logging
  6 import json
  7 """
  8 監控數據採集腳本
  9 採集數據放入redis:
 10     {
 11         host: 'ip地址', 
 12         cpu_parcent: 20%,  # cpu利用率
 13         memory_info: {
 14             total: XXXX, # 總共內存大小
 15             available: XXX, #可用內存
 16             percent: XXX, #內存利用率
 17         },
 18         disk_info: {
 19             total: XXX,
 20             used: XXX.
 21             free: XXX.
 22         }
 23     }
 24 """
 25 
 26 
 27 def bytes2human(n):
 28     symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
 29     prefix = {}
 30     for i, s in enumerate(symbols):
 31         prefix[s] = 1 << (i + 1) * 10
 32     for s in reversed(symbols):
 33         if n >= prefix[s]:
 34             value = float(n) / prefix[s]
 35             return '%.1f%s' % (value, s)
 36     return '%sB' % n
 37 
 38 
 39 def get_memory():
 40     """
 41     獲取內存數據
 42     :return:
 43     """
 44     total_memory = bytes2human(psutil.virtual_memory().total)
 45     available_memory = bytes2human(psutil.virtual_memory().available)
 46     percent_memory = bytes2human(psutil.virtual_memory().percent)
 47     memory_info = {
 48         "total": total_memory,
 49         "available": available_memory,
 50         "percent": percent_memory,
 51     }
 52     return memory_info
 53 
 54 
 55 def get_cpu_parcent():
 56     """
 57     獲取cpu利用率
 58     :return:
 59     """
 60     cpu_parcent = psutil.cpu_percent(interval=1)
 61     return str(cpu_parcent) + "%"
 62 
 63 
 64 def get_host_ip():
 65     """
 66     查詢本機ip地址
 67     :return:
 68     """
 69     try:
 70         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 71         s.connect(('8.8.8.8', 80))
 72         ip = s.getsockname()[0]
 73     finally:
 74         s.close()
 75     return ip
 76 
 77 
 78 def get_disk():
 79     """獲取硬盤信息"""
 80     total = bytes2human(psutil.disk_usage('/').total)
 81     used = bytes2human(psutil.disk_usage('/').used)
 82     free = bytes2human(psutil.disk_usage('/').free)
 83     disk_info = {
 84         "total": total,
 85         "used": used,
 86         "free": free,
 87     }
 88     return disk_info
 89 
 90 
 91 def collection_monitor():
 92     # 建立採集數據的數據結構
 93     ip = get_host_ip()
 94     key = "monior" + str(ip)
 95     cpu_parcent = get_cpu_parcent()
 96     monitor_info = {
 97         "ip": ip,
 98         "cpu_parcent": cpu_parcent,
 99         "memory_info": json.dumps(get_memory()),
100         "disk_info": json.dumps(get_disk()),
101     }
102 
103     conn = redis.Redis(connection_pool=pool, decode_responses=True)
104     try:
105         conn.hmset(key, monitor_info)
106     except Exception as e:
107         logging.debug("redis connect failed,err:%s" % e)
108 
109 
110 
111 if __name__ == '__main__':
112     logging.basicConfig(filename="monior.log", filemode="w", format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
113                         datefmt="%d-%M-%Y %H:%M:%S", level=logging.DEBUG)
114     logging.info('Collcetion Monitor has started')
115     pool = redis.ConnectionPool(host='127.0.0.1', port=6379, password='123456', max_connections=10)
116     logging.info("Redis Connect Success")
117     schedule.every(1).minutes.do(collection_monitor)
118 
119     while True:
120         schedule.run_pending()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章