如何基于py2.6通过企业微信机器人发送tcp连接数告警

背景

  • 这个需求是上上周接到的,当时花了一天的时间就实现了,只是现在才有空记录一篇博客。 这篇博客呢,主要讲一下在python2.6的情况下如何获取shell命令的返回值,如何获取当前已经建立的tcp连接数以及发送消息给企业微信机器人时需要注意的事项,再加上如何简单的使用一下python的第三方定时任务库apscheduler。

环境

  • centos6.9
  • python2.6
  • requests2.16

Github仓库

使用方法

  • 先安装requests库
$ cd tcp_detector/bin && python install.py
  • 修改配置 SCHEDULER_INTERVAL = 5 # 每个多少秒执行一下检测tcp连接数 MAX_ESTABLISHED_TCP_CONNECTION = 5 # tcp连接数达到多少发送告警 QY_WEIXIN_API = “https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" # 企业微信的机器人API地址  

  • 使用

$ python tcp_detector.py &

实现细节

  • 在python2.6的情况下如何获取shell命令的返回值
def check_output(cmd):
        """
        Implementation subprocess.check_output() for Python 2.6
        reference: https://docs.python.org/2/library/subprocess.html#subprocess.Popen
        :param cmd:
        :return: the output of shell command
        """
        process_list = []
        cmd_list = cmd.strip().split("|")
        for i, sub_cmd in enumerate(cmd_list):
            stdin = None
            if i > 0:
                stdin = process_list[i - 1].stdout
            process_list.append(subprocess.Popen(sub_cmd, stdin=stdin, stdout=subprocess.PIPE, shell=True))
        if len(process_list) == 0:
            return ''
        output = process_list[i].communicate()[0]
        return output

这段代码是我google出来的一篇博客上摘录的,出处忘记保存了。有个小问题,output = process_list[i].communicate()[0]这一行中的i变量在for循环外引用运行时竟然没有报错,不知道原作者为啥要这样写,知道的小伙伴欢迎在下方留言哦。

  • 如何获取当前已经建立的tcp连接数
cmd_tcp = "netstat -n | awk '/^tcp/ {++y[$NF]} END {for(w in y) print w, y[w]}'" \
                  " |grep ESTABLISHED | awk -F ' ' '{print $2}'"
  • 发送消息给企业微信机器人时需要注意的事项 当发送的消息的msgtype是默认的text以及http headerapplication/json的时候需要用json.dumps()把消息字典转换为json类型。  

  • 如何简单的使用一下python的第三方定时任务库apscheduler

from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
scheduler.add_job(job.tcp_detecting, 'interval', seconds=SCHEDULER_INTERVAL)
scheduler.start()

这个库即使是一个很低的版本也不兼容python2.6,github仓库中我把这种实现给注释掉了转为使用简单的time.sleep()。在此不得不吐槽一下centos6系列默认的python环境竟然还是2.6。