一、概述
二、python脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/8/20 上午12:42 # @Author : wangying # @Site : # @Software: PyCharm #!/root/.virtualenvs/wechat/bin/python # usage: send message via wechat import requests, sys, json import urllib3 urllib3.disable_warnings() ###填写参数### # Corpid是企业号的标识 Corpid = "ww32a580fceb30f350" # Secret是管理组凭证密钥 Secret = "QyBTbg1QL9lmNwaErqv1DMV0Y_G3lZre268E0hpTDqk" # 应用ID Agentid = "1000004" # token_config文件放置路径 Token_config = r/tmp/zabbix_wechat_config.json ###下面的代码都不需要动### def GetTokenFromServer(Corpid, Secret): """获取access_token""" Url = "" Data = { "corpid": Corpid, "corpsecret": Secret } r = requests.get(url=Url, params=Data, verify=False) print(r.json()) if r.json()[errcode] != 0: return False else: Token = r.json()[access_token] file = open(Token_config, w) file.write(r.text) file.close() return Token def SendMessage(Partyid, Subject, Content): """发送消息""" # 获取token信息 try: file = open(Token_config, r) Token = json.load(file)[access_token] file.close() except: Token = GetTokenFromServer(Corpid, Secret) # 发送消息 Url = "" % Token Data = { "toparty": Partyid, "msgtype": "text", "agentid": Agentid, "text": { "content": Subject +
+ Content}, "safe": "0" } r = requests.post(url=Url, data=json.dumps(Data), verify=False) # 如果发送失败,将重试三次 n = 1 while r.json()[errcode] != 0 and n < 4: n = n + 1 Token = GetTokenFromServer(Corpid, Secret) if Token: Url = "" % Token r = requests.post(url=Url, data=json.dumps(Data), verify=False) print(r.json()) return r.json() if __name__ == __main__: # 部门id Partyid = 20 # 消息标题 Subject = 自应用程序代码测试 # 消息内容 Content = str(sys.argv[3]) Status = SendMessage(Partyid, Subject, Content) print(Status)
下行是linux环境下python3的可执行路径,如果是windows,那么这行就不需要,只要将python的路径加入到path即可
#!/root/.virtualenvs/wechat/bin/python
# Corpid是企业ID
Corpid = "ww34d7fed41a8d5dxx"
# Secret是管理组凭证密钥
Secret = "8QwzOi0xCvbp1ZnCbnQJ1d6uEIv-Lrbcjp93UrHFxxx"
# Agentid是应用ID
Agentid = "1000002"
# Token_config里面存放token信息,这个自己随便填就行,只要自己有写的权限
Token_config = r/tmp/zabbix_wechat_config.json
2. 点击进入管理后台
创建应用
3. 创建应用完成后
Agentid,Secret就出来了
4. 查看企业id
这个就是脚本中的Corpid
5. 查看部门id
我这个python脚本是通过部门id进行群体发送,所以这个部门id到后面会有用。
四、测试脚本
直接运行:python manage.py runserver