监控redis python脚本

#!/bin/env python
#-*- coding:utf-8 -*-

import json
import time
import socket
import os
import re
import sys
import commands
import urllib2, base64

class RedisStats:
redis_cli = ‘/data/redis/bin/redis-cli‘
stat_regex = re.compile(ur‘(\w+):([0-9]+\.?[0-9]*)\r‘)

def __init__(self,port=‘6379‘,passwd=None,host=‘127.0.0.1‘,status=‘info‘):
self.cmd = ‘%s -h %s -p %s %s‘ % (self.redis_cli, host, port,status)

def stats(self):
info = commands.getoutput(self.cmd)
return dict(self.stat_regex.findall(info))

def main():
timestamp = int(time.time())
step = 60

p = []

monit_keys = [
(‘connected_clients‘,‘GAUGE‘),
(‘blocked_clients‘,‘GAUGE‘),
(‘used_memory‘,‘GAUGE‘),
(‘used_memory_rss‘,‘GAUGE‘),
(‘mem_fragmentation_ratio‘,‘GAUGE‘),
(‘total_commands_processed‘,‘COUNTER‘),
(‘rejected_connections‘,‘COUNTER‘),
(‘expired_keys‘,‘COUNTER‘),
(‘evicted_keys‘,‘COUNTER‘),
(‘keyspace_hits‘,‘COUNTER‘),
(‘keyspace_misses‘,‘COUNTER‘),
(‘keyspace_hit_ratio‘,‘GAUGE‘),
]

insts_list = [ ‘/etc/redis/6379.conf‘ ]

with open(‘./cfg.json‘) as f:
data = f.read().replace(‘\n‘,‘‘)
jsonhostname = json.loads(data)
hostpoint = jsonhostname[‘hostname‘]

for inst in insts_list:
port = commands.getoutput("sed -n ‘s/^port *\([0-9]\{4,5\}\)/\\1/p‘ %s" % inst)
metric = "redis"
endpoint = ‘%s‘ %(hostpoint)
tags = ‘port=%s‘ % port

try:
conn = RedisStats()
stats = conn.stats()
except Exception,e:
continue

for key,vtype in monit_keys:
if key == ‘keyspace_hit_ratio‘:
try:
value = float(stats[‘keyspace_hits‘])/(int(stats[‘keyspace_hits‘]) + int(stats[‘keyspace_misses‘]))
except ZeroDivisionError:
value = 0
elif key == ‘mem_fragmentation_ratio‘:
value = float(stats[key])
else:
try:
value = int(stats[key])
except:
continue

i = {
‘Metric‘: ‘%s.%s‘ % (metric, key),
‘Endpoint‘: endpoint,
‘Timestamp‘: timestamp,
‘Step‘: step,
‘Value‘: value,
‘CounterType‘: vtype,
‘TAGS‘: tags
}
p.append(i)

print json.dumps(p, sort_keys=True,indent=4)
method = "POST"
handler = urllib2.HTTPHandler()
opener = urllib2.build_opener(handler)
url = ‘http://127.0.0.1:1988/v1/push‘
request = urllib2.Request(url, data=json.dumps(p) )
request.add_header("Content-Type",‘application/json‘)
request.get_method = lambda: method
try:
connection = opener.open(request)
except urllib2.HTTPError,e:
connection = e

# check. Substitute with appropriate HTTP code.
if connection.code == 200:
print connection.read()
else:
print ‘{"err":1,"msg":"%s"}‘ % connection
if __name__ == ‘__main__‘:
proc = commands.getoutput(‘ ps -ef|grep %s|grep -v grep|wc -l ‘ % os.path.basename(sys.argv[0]))
if int(proc) < 5:
main()

#!/bin/env python
#-*- coding:utf-8 -*-

import json
import time
import socket
import os
import re
import sys
import commands
import urllib2, base64

class RedisStats:
    redis_cli = ‘/data/redis/bin/redis-cli‘
    stat_regex = re.compile(ur‘(\w+):([0-9]+\.?[0-9]*)\r‘)

    def __init__(self,port=‘6379‘,passwd=None,host=‘127.0.0.1‘,status=‘info‘):
        self.cmd = ‘%s -h %s -p %s %s‘ % (self.redis_cli, host, port,status)

    def stats(self):
        info = commands.getoutput(self.cmd)
        return dict(self.stat_regex.findall(info))

def main():
    timestamp = int(time.time())
    step = 60

    p = []

    monit_keys = [
        (‘connected_clients‘,‘GAUGE‘),
        (‘blocked_clients‘,‘GAUGE‘),
        (‘used_memory‘,‘GAUGE‘),
        (‘used_memory_rss‘,‘GAUGE‘),
        (‘mem_fragmentation_ratio‘,‘GAUGE‘),
        (‘total_commands_processed‘,‘COUNTER‘),
        (‘rejected_connections‘,‘COUNTER‘),
        (‘expired_keys‘,‘COUNTER‘),
        (‘evicted_keys‘,‘COUNTER‘),
        (‘keyspace_hits‘,‘COUNTER‘),
        (‘keyspace_misses‘,‘COUNTER‘),
        (‘keyspace_hit_ratio‘,‘GAUGE‘),
    ]

    insts_list = [ ‘/etc/redis/6379.conf‘ ]

    with open(‘./cfg.json‘) as f:
        data = f.read().replace(‘\n‘,‘‘)
        jsonhostname = json.loads(data)
        hostpoint = jsonhostname[‘hostname‘]

    for inst in insts_list:
        port = commands.getoutput("sed -n ‘s/^port *\([0-9]\{4,5\}\)/\\1/p‘ %s" % inst)
        metric = "redis"
        endpoint = ‘%s‘ %(hostpoint)
        tags = ‘port=%s‘ % port

        try:
            conn = RedisStats()
            stats = conn.stats()
        except Exception,e:
            continue

        for key,vtype in monit_keys:
            if key == ‘keyspace_hit_ratio‘:
                try:
                    value = float(stats[‘keyspace_hits‘])/(int(stats[‘keyspace_hits‘]) + int(stats[‘keyspace_misses‘]))
                except ZeroDivisionError:
                    value = 0
            elif key == ‘mem_fragmentation_ratio‘:
                value = float(stats[key])
            else:
                try:
                    value = int(stats[key])
                except:
                    continue

            i = {
                ‘Metric‘: ‘%s.%s‘ % (metric, key),
                ‘Endpoint‘: endpoint,
                ‘Timestamp‘: timestamp,
                ‘Step‘: step,
                ‘Value‘: value,
                ‘CounterType‘: vtype,
                ‘TAGS‘: tags
            }
            p.append(i)

    print json.dumps(p, sort_keys=True,indent=4)
    method = "POST"
    handler = urllib2.HTTPHandler()
    opener = urllib2.build_opener(handler)
    url = ‘http://127.0.0.1:1988/v1/push‘
    request = urllib2.Request(url, data=json.dumps(p) )
    request.add_header("Content-Type",‘application/json‘)
    request.get_method = lambda: method
    try:
        connection = opener.open(request)
    except urllib2.HTTPError,e:
        connection = e

    # check. Substitute with appropriate HTTP code.
    if connection.code == 200:
        print connection.read()
    else:
        print ‘{"err":1,"msg":"%s"}‘ % connection
if __name__ == ‘__main__‘:
    proc = commands.getoutput(‘ ps -ef|grep %s|grep -v grep|wc -l ‘ % os.path.basename(sys.argv[0]))
    if int(proc) < 5:
        main()
时间: 2025-01-05 23:48:47

监控redis python脚本的相关文章

zabbix 监控redis python3脚本

一:安装redis-python模块 wge  thttps://pypi.python.org/packages/source/r/redis/redis-2.9.1.tar.gz tar xf redis-2.9.1.tar.gz cd redis-2.9.1 python setup.py install 二:配置zabbix (1) 将zabbix-redis.py 放入到/usr/local/zabbix/etc/scripts目录下 (2) 更改zabbix_agentd.conf

zabbix监控利用Python脚本发邮件

最近实施了zabbix监控,开源软件杠杠的,甩nagios 好几条街-- 环境:centos6.6 + Zabbix 2.4.5 + Python 2.6.6 cd /usr/local/zabbix/share/zabbix/alertscripts #进入脚本存放目录vi SendAlertEmail.sh #编辑,添加以下代码#!/bin/shecho "$3" | mail -s "$2" $1:wq! #保存退出chown zabbix.zabbix /u

监控url python脚本

python代码: #!/usr/bin/python #coding:utf-8 import StringIO import pycurl import sys import os class urlpass: def __init__(self): self.contents = '' def body_callback(self,buf): self.contents = self.contents + buf def urlgzip(input_url): t = urlpass()

lamp环境加glusterfs存储集群自动化监控自动修复python脚本

#!/usr/bin/python#coding:utf-8import osimport sysimport reimport paramikoimport commandsimport timeimport datetime def apache_connect_perform(ip,command):client = paramiko.SSHClient()client.set_missing_host_key_policy(paramiko.AutoAddPolicy())client.

falcon监控redis

falcon 结合脚本redis-monitor.py进行监控redis * * * * * python /usr/local/openfalcon-0.2/mymon/redis-monitor.py &> /usr/local/openfalcon-0.2/mymon/redis-monitor.log cat redis-monitor.py #注意修改配置项:_redis_cli,def __init__,insts_list,ip #!/bin/env python #-*- c

监控redis和zookpeer服务脚本 并且python发送邮件

监控rediszookpeer #!/bin/bash name=`cat /etc/salt/minion | grep "^id" | awk '{print $2}'` ipaddr=`/sbin/ifconfig | grep "inet addr" | egrep -v "10\.|127\." | awk  -F'[: ]+' '{print $4}'` function checkRedis(){     ps="`ps 

Redis之使用python脚本监控队列长度

编辑python脚本redis_conn.py #!/usr/bin/env python #ending:utf-8 import redis def redis_conn(): pool = redis.ConnectionPool(host="192.168.56.11",port=6379,db=3,password=123456) conn = redis.Redis(connection_pool=pool) data = conn.llen("system-lo

一个简单的监控redis性能的python脚本

一个简单的监控redis性能的python脚本 上一篇已经讲了如何监控memcached了,现在也顺带讲如何监控redis. 首先介绍下监控redis那些信息: Redis ping:检验ping Redis alive:查看检查端口是否alive Redis connections:查看连接数 Redis blockedClients:正在等待阻塞客户端数量 Redis connectionsUsage:redis的连接使用率 Redis memoryUsage:redis内存使用量 Redi

用 Python 脚本实现对 Linux 服务器的监控

hon 分享到:8 原文出处: 曹江华 目前 Linux 下有一些使用 Python 语言编写的 Linux 系统监控工具 比如 inotify-sync(文件系统安全监控软件).glances(资源监控工具)在实际工作中,Linux 系统管理员可以根据自己使用的服务器的具体情况编写一下简单实用的脚本实现对 Linux 服务器的监控. 本文介绍一下使用 Python 脚本实现对 Linux 服务器 CPU 内存 网络的监控脚本的编写. Python 版本说明 Python 是由 Guido va