欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

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

程序员文章站 2022-05-07 11:22:33
...

用途: 批量删除当前连接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!