python发送钉钉消息通用脚本
1、使用shell生成需要发送的内容。
2、调用该脚本发送文本内容python3,其中的文件 /wj/sbjk,需要改成直接需要发送的文件。
[root@manager dingding]# more sed-py.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import base64
import hashlib
import hmac
import time
import urllib.parse
import requests
import json
class DingTalkWarn:
"""钉钉消息通知"""
def __init__(self):
# 安全设置使用加签方式
timestamp = str(round(time.time() * 1000))
# 刚才记录下来的签名
secret = 'SECd25e3c8aa1acec9bf6a0ed876b7e79bd13032453e858350f56280396208848e6'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
# 以上就是加签的安全配置,其它安全设置,无需配置以上信息
# webhook地址(刚才记录的webhook)
webhook = 'https://oapi.dingtalk.com/robot/send?access_token=716f0a3ec23e18393aec4c01a3116f48cc55abb45f20a166c3c4d8b0654f911d'
# 如果你的不是加签的安全方式,即可省去 ×tamp={}&sign={} 部分参数
self.webhook = "{}×tamp={}&sign={}".format(webhook, timestamp, sign)
# 配置请求headers
self.headers = {
"Content-Type": "application/json",
"Charset": "UTF-8" # 发起POST请求时,必须将字符集编码设置成UTF-8。
}
def send_text_msg(self, content, at_mobiles=None, is_at_all=False):
message = {
"msgtype": "text", # 消息类型
"text": {
"content": content
},
"at": {
"atMobiles": at_mobiles,
"isAtAll": is_at_all
}
}
self.send_req(message) # 发送消息
def send_req(self, message):
# 将请求数据进行json数据封装
form_data = json.dumps(message)
# 发起请求
res_info = requests.post(url=self.webhook, headers=self.headers, data=form_data)
# 打印返回的结果
print(u'邮件发送结果:', res_info.json())
print(u'通知成功!' if (res_info.json())['errmsg'] == 'ok' else u'通知失败!')
if __name__ == '__main__':
"""测试发送消息"""
#文本方式 读取文本sbjk,使用的时候需要修改文本名称路径必须绝对路径
l = '/wj/sbjk'
f = open(l, 'rt', encoding='utf-8')
content = f.read()
print(content)
DingTalkWarn().send_text_msg(content)
f.close()
3、调用方式shell中调用python脚本
[root@manager dingding]# more check.sh
#!/bin/bash
source /etc/profile
w=$(cd $(dirname $0);pwd)
jg=`cat $w/sbjk`
if [ -n "$jg" ]
then
/usr/bin/python3 $w/sed-py.py
else
echo '全部成功'
fi
4、定时任务,每10秒钟运行一次的配置
* * * * * sleep 10; /wj/dingding/a * * * * * sleep 20; /wj/dingding/a * * * * * sleep 30; /wj/dingding/a * * * * * sleep 40; /wj/dingding/a * * * * * sleep 50; /wj/dingding/a
做一个决定,并不难,难的是付诸行动,并且坚持到底。

浙公网安备 33010602011771号