Python小功能-发送钉钉信息

Python小功能-发送钉钉消息

可根据自己情况进行修改

# coding: utf-8

import json
import requests
import time
import socket 
import sys

def dingding_robot(data):
    # token地址 需要修改
    dingding_robot_token = "https://oapi.dingtalk.com/robot/send?access_token=d8ebca52d6ac9546895670f1bxxxxx"

    headers = {'content-type': 'application/json'}
    r = requests.post(dingding_robot_token, headers=headers, data=json.dumps(data))
    r.encoding = 'utf-8'
    return (r.text)
# get ip 
def get_host_ip():
    try:
        s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(('114.114.114.114',80))
        ip=s.getsockname()[0]
    finally:
        s.close()
    return ip

if __name__ == "__main__":
    ip = get_host_ip()
    role = sys.argv[1]
    data = {
        "msgtype": "markdown", 
        #告警内容,需要调整
        "markdown": {
                    "title": "Nginx Keepalived监控",
                    "text": "### %s Change to %s\n\n" % (ip,role) + 
                    "> #### Nginx Keepalived状态监控\n\n" + 
                    "> #### VIP: 192.168.1.1 \n\n" + 
                    "> #### 时间: %s\n" % time.strftime("%Y-%m-%d %X") +
                    "> #### 服务名:keepalived \n\n"  +
                    "> #### 状态:切换 \n\n" +
                    "> ##### Nginx VIP监控\n\n后端机器IP:192.168.1.2/3 Master为192.168.1.2\n\n状态切换请检查备机"
        },
    }
    res = dingding_robot(data)
    print (res)

效果图

此脚本是配合keepalived的监控操作,当主发生切换的时候,告知主已切换,备切换的时候告知备已切换
python   *.py   Master  
python   *.py   Backup  

转载于:https://blog.51cto.com/14080948/2318805

你可能感兴趣的:(Python小功能-发送钉钉信息)