zabbix监控单机多实例redis脚本
公司节省成本,充分利用资源,部署了单机多实例的线上情况。 作为python新手,果断决定写个很low的脚本,然后实现监控功能。
下面这个脚本实现了,discovery自动发现,然后通过一个status监控实现了,其它监控信息的自动汇报功能。 其中很low的地方在于,每个主机上的脚本必须定义本地的redis信息,比如端口,密码之类的;其实这个可以通过配置中心获取的,但是因为分享出来,所以就写了个定义的实例;还有一点大神都一般自己写socket发送数据,我这里很简单,通过shell,使用简单省事的方法。
#!/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])