代码如下:
import time import hmac import hashlib import base64 import urllib import json import requests class DingTalkRobot(object): def __init__(self, webhook, sign=None): self.webhook = webhook self.sign = sign self.headers = {'Content-Type': 'application/json; charset=utf-8'} self.times = 0 self.start_time = time.time() def splice_url(self): """加密签名""" timestamp = int(round(time.time() * 1000)) secret = self.sign 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)) """ 注意此处两处字符串拼接写法 第一行可以应用于python3.6版本 第二行可以应用python2版本 """ # url = f'{self.webhook}×tamp={timestamp}&sign={sign}' url = '{}×tamp={}&sign={}'.format(self.webhook,timestamp,sign) return url def send_text(self, msg): data = {"msgtype": "text", "at": {}} if msg: data["text"] = {"content": msg} else: return {'errcode': 500, 'errmsg': '消息内容不能为空'} return self.__post(data) def __post(self, data): post_data = json.dumps(data) try: response = requests.post(self.splice_url(), headers=self.headers, data=post_data) except Exception: return {'errcode': 500, 'errmsg': '服务器响应异常'} result = response.json() return result ipList = ['128.1.87.103', '156.236.93.49', '156.236.93.38', '10.67.123.27', '10.110.196.85'] ip_List = '\n'.join(ipList) #将列表转换未换行输出的字符串 if __name__ == '__main__': URL = "钉钉Webhook" SIGN = "密钥" ding = DingTalkRobot(URL, SIGN) ding.send_text("请注意!\n机器列表如下:\n"+ip_List)