#!/usr/bin/env python
\# -*- coding: utf-8 -*-
\# Author: 刘小懒
\# example:python dingding.py 参数1 参数2 参数3
import requests
import json
import sys
import os
import time
headers = {'Content-Type': 'application/json'}
time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
log_dir = '/usr/local/zabbix/logs/'
log_file = 'dingding.log'
api_url = '钉钉的Webhook地址'
def log(info):
# 注意权限,否则写不进去日志
file\_path = log\_dir + log_file
if os.path.isdir(log_dir) == False:
os.makedirs(log_dir)
elif os.path.isfile(file_path) == False:
f = open(file_path,'a+')
f.write(info)
f.close()
else:
f = open(file_path, 'ab+')
f.write(info)
f.close()
def msg(text, user):
json_text= {"msgtype": "text","text": {"content": text},"at": {"atMobiles": \[user\],"isAtAll": False}}
r=requests.post(api\_url,data=json.dumps(json\_text),headers=headers).json()
code = r\["errcode"\]
if code == 0:
log(time + ":消息发送成功 返回码:" + str(code) + "\\n")
else:
log(time + ":消息发送失败 返回码:" + str(code) + "\\n")
exit(3)
if \_\_name\_\_ == '\_\_main\_\_':
text = sys.argv\[3\]
user = sys.argv\[1\]
msg(text,user)
#### 这个代码有很多地方可以优化,请自行优化
#### python运维交流群: 305357273