Luocs玩Python之:批量杀掉Redis客户端连接

WBOY
發布: 2016-06-07 16:41:30
原創
1898 人瀏覽過

用途: 批量删除当前连接redis的所有客户端,除了从库的IP和本机IP。 准备一个hosts.txt配置,里面按如下格式填写Redis集群信息# cat hosts.txt[test]h1 = 1.1.1.1h2 = 1.1.1.2h3 = 1.1.1.3[group1]h1 = 2.1.1.1h2 = 2.1.1.2h3 = 2.1.1.3# cat killclient.py

用途: 批量删除当前连接redis的所有客户端,除了从库的IP和本机IP。

准备一个hosts.txt配置,里面按如下格式填写Redis集群信息
# cat hosts.txt
[test]
h1 = 1.1.1.1
h2 = 1.1.1.2
h3 = 1.1.1.3
[group1]
h1 = 2.1.1.1
h2 = 2.1.1.2
h3 = 2.1.1.3
# cat killclient.py 
#!/usr/bin/env python 
# -*- coding: UTF-8 -*-
###################################################### 
# @Author:       Luocs(XU)  
# @Create Date:  2014-12-18
######################################################
import os, sys, time, ConfigParser
def killclient(clicmd, host, port, s1, s2, myip):
    os.popen("cat /dev/null > /tmp/client.tmp")
    os.popen("%s -h %s -p %s client list >> /tmp/client.tmp" % (clicmd, host, port))
    f = open("/tmp/client.tmp")
    while 1:
        line = f.readline().strip()
        if not line:
            break
        myclient = os.popen("echo %s | grep -v -E '%s|%s|%s' | awk '{print $2}' | awk -F'=' '{print $2}'" % (line, s1, s2, myip)).read().strip()
        if myclient:
            print("Client %s killed!" % myclient)
            os.popen("%s -h %s -p %s client kill %s" % (clicmd, host, port, myclient))
def getMyip():
    myip = os.popen("/sbin/ifconfig | grep 'inet addr' | awk '{print $2}'").read()
    myip = myip[myip.find(':')+1:myip.find('\n')]
    return myip
def gethost(name):
    fp = ConfigParser.ConfigParser()
    fp.readfp(open('hosts.txt'))
    h1 = fp.get(name,"h1") # 主库的IP
    h2 = fp.get(name,"h2") # 从库IP
    h3 = fp.get(name,"h3") # 从库IP,有多少个可以继续写下去
    return h1, h2, h3
def main():
    name = sys.argv[1]
    port = sys.argv[2]
    #port = 7001 # 也可以写死
    clicmd = "/home/luocs/redis-cli" # redis-cli
    h1, h2, h3 = gethost(name)
    host = h1 # 主库ip传给host
    s1 = h2 
    s2 = h3
    myip = getMyip()
    killclient(clicmd, host, port, s1, s2, myip)
if __name__ == '__main__':
    main()
执行结果:
# python killclient.py test 7001
Client 127.0.0.1:58263 killed!
Client 127.0.0.1:58264 killed!
Client 127.0.0.1:58265 killed!
Client 127.0.0.1:58266 killed!
Client 127.0.0.1:58267 killed!
Client 127.0.0.1:58268 killed!
Client 127.0.0.1:58269 killed!
登入後複製
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板