公司節省成本,充分利用資源,部署了單機多實例的線上狀況。
做爲python新手,果斷決定寫個很low的腳本,而後實現監控功能。python
下面這個腳本實現了,discovery自動發現,而後經過一個status監控實現了,其它監控信息的自動彙報功能。
其中很low的地方在於,每一個主機上的腳本必須定義本地的redis信息,好比端口,密碼之類的;其實這個能夠經過配置中心獲取的,可是由於分享出來,因此就寫了個定義的實例;還有一點大神都通常本身寫socket發送數據,我這裏很簡單,經過shell,使用簡單省事的方法。redis
#!/usr/bin/env python3.6 """ @author:zmoke @file: redis_monitor.py @version: @time: 2019/04/24 @email:zmoke1792@gmail.com @function: """ import redis import subprocess import sys import json class RedisApi(object): def __init__(self, name, redis_message): self.__redis_addr = redis_message[name][0] self.__redis_port = redis_message[name][1] self.__redis_password = redis_message[name][2] self.__zabbix_sender = '/usr/local/zabbix/bin/zabbix_sender' self.__zabbix_conf = '/usr/local/zabbix/conf/zabbix_agentd.conf' def connect(self): # 創建鏈接 try: pool = redis.ConnectionPool(host=self.__redis_addr, port=self.__redis_port, db=None, password=self.__redis_password) connection = redis.Redis(connection_pool=pool) return connection except Exception as e: print('redis connect err :%s' % e) def send_message(self, key, msg): zabbix_sender = self.__zabbix_sender, zabbix_conf = self.__zabbix_conf try: subprocess.Popen([zabbix_sender, "-c", zabbix_conf, "-k", key, "-o", msg], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # print "send zabbix success" except Exception as e: print(f"Something went wrong while exectuting zabbix_sender : {e}") if __name__ == "__main__": redis_message = {'test1': ['127.0.0.1', 6379, None], 'test2': ['127.0.0.1', 6382, None]} name = sys.argv[1] if name == 'discovery': data = { "data": [ ] } for message in redis_message.keys(): # print(redis_message[message][1]) data["data"].append({"{#REDISPORT}": redis_message[message][1]}) print(json.dumps(data, sort_keys=True, indent=4)) else: api = RedisApi(name, redis_message=redis_message) con = api.connect() if con.ping(): print(0) else: print(1) messages = con.info() for key in messages.keys(): if key.startswith('db'): pass else: monitor_key = f'Redis.Info[{key}, {redis_message[name][1]}]' print(monitor_key, ":", messages[key]) # api.send_message(key=key, msg=messages[key])