python实现Zabbix图文告警,代码如下:
#!/usr/bin/python
# coding: utf-8
#Author: Zhi Li
import urllib.request
import json
import sys
import datetime,time
import os
import argparse
import re
import requests
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
######################################
#可以访问到zabbix页面的URL
URL = 'http://IP/zabbix/api_jsonrpc.php'
ZABBIX_URL='http://IP/zabbix/index.php'
CHART_URL='http://IP/zabbix/chart.php'
#登录zabbix的账号密码
USERNAME='Admin'
PASSWORD='umpayzabbix'
#放cookie的路径
COOKIEURL='/usr/local/zabbix3/alertscripts/cookie'
#方式图片的路径
PIC_PATH ='/usr/local/zabbix3/alertscripts/image/'
#微信企业号
corpsecret ="RpbDsLX9j5SapI-FGslq1V4aAZujbnQP4w2yohkUTPU"
corpid = "ww21e0a9f6c3eaa8b8"
agentid='1000002'
######################################
#获取上传图片至微信服务器返回的id
def getMediaId(ip,key,auth,USERNAME,PASSWORD,COOKIEURL,ZABBIX_URL,PIC_PATH,CHART_URL):
###sessionID写入cookie文件
curlcookie="curl -c {} -b {} -d 'name={}&password={}&autologin=1&enter=Sign+in' {}".format(COOKIEURL,COOKIEURL,USERNAME,PASSWORD,ZABBIX_URL)
a=os.system(curlcookie)
#通过ip获取hostid+graphname进而获取graphids
hostids=ipgetHostsid(ip,URL,auth)
print("hostids:",hostids)
hostid=int(hostids[0]['hostid'])
itemids=getitemid(hostid,key,URL,auth)
itemid=itemids[0]["itemid"]
###获取一小时前时间
timedata=datetime.datetime.now()-datetime.timedelta(seconds=5)
stime=timedata.strftime("%Y%m%d%H%M%S")
print (stime)
##保存图片文件至本地
PIC_URL = "{}graph.{}.png".format(PIC_PATH,stime)
print("PIC_URL:",PIC_URL)
curlgraph='curl -b {} -d "itemids={}&period=3600&time={}&width=1200" {} >{}'.format(COOKIEURL,itemid,stime,CHART_URL,PIC_URL)
print ("curlgraph:",curlgraph)
b=os.system(curlgraph)
print("b",b)
#上传图片至企业微信
M_URL="https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={}&type=image".format(accesstoken)
print("M_URL:",M_URL)
#获取上传图media_id
files={'image': open(PIC_URL, 'rb')}
r =requests.post(M_URL, files=files)
print("r:",r)
media_id=json.loads(r.content)
print ("media_id:",media_id)
return media_id["media_id"]
#获取微信accsss_token
def gettoken():
Time1=os.popen("grep 'gettime' /usr/local/zabbix3/alertscripts/Token.txt | awk -v FS='=' '{print $2}'").readlines()
Time2=time.strftime("%Y-%m-%d %H:%M:%S")
date1 = time.strptime(Time1[0].strip().replace('"',""), "%Y-%m-%d %H:%M:%S")
date2 = time.strptime(Time2, "%Y-%m-%d %H:%M:%S")
date3 = datetime.datetime(date1[0], date1[1], date1[2], date1[3], date1[4], date1[5])
date4 = datetime.datetime(date2[0], date2[1], date2[2], date2[3], date2[4], date2[5])
DValue=(((date4 - date3).seconds) // 3600 )
Ago_Access_Token=os.popen("grep 'access_token' /usr/local/zabbix3/alertscripts/Token.txt | awk -v FS='=' '{print $2}'").readlines()
Ago_Access_Token=Ago_Access_Token[0].strip().replace('"',"")
if DValue >= 2:
tokenURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}".format("ww21e0a9f6c3eaa8b8","RpbDsLX9j5SapI-FGslq1V4aAZujbnQP4w2yohkUTPU")
token_file = urllib.request.urlopen(tokenURL)
token_data = token_file.read().decode('utf-8')
token_json = json.loads(token_data)
token_json.keys()
token = token_json['access_token']
Time1 = Time1[0].strip().replace('"',"")
os.environ['Ago_Access_Token'] = str(Ago_Access_Token.strip())
os.environ['token'] = str(token.strip())
os.environ['Time1'] = str(Time1.strip())
os.environ['Time2'] = str(Time2.strip())
os.popen("sed -i "s%$Time1%$Time2%g" /usr/local/zabbix3/alertscripts/Token.txt").readlines()
os.popen("sed -i 's%'$Ago_Access_Token'%'$token'%g' /usr/local/zabbix3/alertscripts/Token.txt").readlines()
return token
else:
return Ago_Access_Token
#发送图文信息
def senddata(access_token,user,agentid,title,content,MEDIA_ID):
PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token
print ("PURL:",PURL)
send_values = {
"touser":user,
"msgtype":"mpnews",
"agentid":agentid,
"mpnews": {
"articles":[
{
"title": title,
"thumb_media_id": MEDIA_ID,
"author": "zabbix",
"content":content,
"digest": content
},
]
},
}
send_data = json.dumps(send_values, ensure_ascii=False)
send_data = bytes(send_data,'utf-8')
print ("send_data:",send_data)
send_request = urllib.request.Request(PURL, send_data)
response = json.loads(urllib.request.urlopen(send_request).read())
print (str(response))
#定义通过HTTP方式访问API地址的函数,后面每次请求API的各个方法都会调用这个函数
def requestJson(URL,values):
post_header={'Content-Type': 'application/json'}
req = requests.post(URL,data=json.dumps(values),headers=post_header)
response = json.loads(req.text)
try:
message = response.get('result')
except:
quit()
return response.get('result')
#API接口认证的函数,登录成功会返回一个Token
def authenticate(URL, USERNAME, PASSWORD):
values = {'jsonrpc': '2.0',
'method': 'user.login',
'params': {
'user': '{}'.format(USERNAME),
'password': '{}'.format(PASSWORD)
},
'id': '0'
}
idvalue = requestJson(URL,values)
return idvalue
#zabbix api通过ip获取主机id
def ipgetHostsid(ip,URL,auth):
values = {'jsonrpc': '2.0',
'method': 'host.get',
'params': {
'output': [ "host" ],
'filter': {
'ip': ip
},
},
'auth': auth,
'id': '3'
}
output = requestJson(URL,values)
print("ouput:",output)
return output
#zabbix api 通过hostid获取itemid的函数
def getitemid(hostid,key,URL,auth):
values = {'jsonrpc': '2.0',
'method': 'item.get',
'params': {
"output": "itemid",
"hostids": hostid,
"search": {
"key_": key
},
"sortfield": "name",
},
'auth': auth,
'id': '21'
}
output = requestJson(URL,values)
return output
if __name__ == '__main__':
auth = authenticate(URL, USERNAME, PASSWORD)
user = str(sys.argv[1]) #微信企业号账号标识
title = str(sys.argv[2]) #zabbix传过来的第一个参数-标题
content = str(sys.argv[3]) #zabbix传过来的第二个参数-内容
ip=re.findall(r"主机IP:(.+?)<br>",content)[0]#截取ip地址
key=re.findall(r"告警项目:(.+?)<br>",content)[0]#截取zabbix key
#####测试
#ip="192.168.1.2"
#key="proc.num[]"
#获取token
accesstoken = gettoken()
print("accesstoken:",accesstoken)
#获取图片id
MEDIA_ID=getMediaId(ip,key,auth,USERNAME,PASSWORD,COOKIEURL,ZABBIX_URL,PIC_PATH,CHART_URL)
os.popen("chown -R zabbix.zabbix /usr/local/zabbix3/alertscripts/image/*")
#发送图文
senddata(accesstoken,user,agentid,title,content,MEDIA_ID)