共计 1702 个字符,预计需要花费 5 分钟才能阅读完成。
背景
- 这个需求是上上周接到的,当时花了一天的时间就实现了,只是现在才有空记录一篇博客。这篇博客呢,主要讲一下在 python2.6 的情况下如何获取 shell 命令的返回值,如何获取当前已经建立的 tcp 连接数以及发送消息给企业微信机器人时需要注意的事项,再加上如何简单的使用一下 python 的第三方定时任务库 apscheduler。
环境
- centos6.9
- python2.6
- requests2.16
Github 仓库
- https://github.com/supersu097/tcp_detector.git
使用方法
- 先安装 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 header
为application/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。
正文完
发表至: Python编程
2020-01-13