Python 简单脚本对接钉钉机器人

时间:2022-08-16 08:48:27

本脚本是简单调用钉钉api接口实现报警

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: Mr.xiong
# Date: 20190329

import requests
import json
import os
import time

headers = {'Content-Type': 'application/json'}
hostname = os.popen("hostname").read().strip()
apiurl = "https://oapi.dingtalk.com/robot/send?access_token=8afz79e4381784a3938f4e68303e5bd31e640c5ce556ece86801d76a5028c258"


def monitor():
    li = []
    text = """
    【xx科技】故障: socket在线用户数趋势监测 > 100

     告警主机: {}

     告警时间: {}

     问题详情: socketonlineuser

     当前状态: {}
    """
    while True:
        fp = open('/tmp/socketuser.log', 'a', encoding='utf-8')
        r = os.popen("curl http://10.10.17.32:9099/ping 2>/dev/null").read()
        d = json.loads(r)
        onlineuser = d["onlineuser"]
        currOnline = d["currOnline"]
        if len(li) < 2:
            li.append(onlineuser)
        elif len(li) == 2:
            li.pop()
            li.append(onlineuser)
            time.sleep(60)
            abscount = abs(li[1] - li[0])
            if abscount == 0:
                currenttime = time.strftime("%Y-%m-%d %X")
                value = text.format(hostname, currenttime, currOnline)
                json_text = {"msgtype": "text", "text": {"content": value}}
                rep = requests.post(apiurl, data=json.dumps(json_text), headers=headers).json()
                code = rep["errcode"]
                if code == 0:
                    fp.write(currenttime + ":消息发送成功 返回码:" + str(code) + "\n")
                else:
                    fp.write(currenttime + ":消息发送失败 返回码:" + str(code) + "\n")
                fp.close()


if __name__ == '__main__':
    monitor()