刚写完年费用记录,再水一篇。
这个是 Zabbix 的 alertscripts 脚本,用于报警消息发送到 Telegram,需要先在 @BotFather 创建一个机器人。
# cat /usr/local/zabbix/share/zabbix/alertscripts/telegram.py
#!/usr/local/bin/python2.7
# -*- coding:utf-8 -*-
# Powered by myluoluo
import os,sys,smtplib,requests,MySQLdb,codecs,time,json
to = sys.argv[1] # Telegram 用户 ID
subject = sys.argv[2]
body = sys.argv[3]
servicesUrl = 'https://api.telegram.org/bot{TOKEN}/sendPhoto'
print(servicesUrl)
# Zabbix 数据库连接信息
mysql_server= "127.0.0.1"
mysql_user = "zabbix"
mysql_pass = "zabbix"
db_name = "zabbix"
# Zabbix 后台地址以及登录信息
zabbix_url = "https://zabbix.domain.com"
zabbix_user = "admin"
zabbix_pass = "admin"
# 需要设定文件夹所属:
# chown zabbix:zabbix /home/wwwroot/default/zabbix-graph/
image_path = "/home/wwwroot/default/zabbix-graph/" + os.popen('date +%Y%m').read().rstrip() + "/"
image_url = "https://zabbix.domain.com/zabbix-graph/" + os.popen('date +%Y%m').read().rstrip() + "/"
stime = os.popen('date +%Y%m%d%H%M%S').read().rstrip()
period = 3600 # 秒
cookie = "/tmp/cookie"
width = 1222
# 事件详细信息地址
def getEvent(body):
tmp = body.split('Original event ID: ')
if any(tmp) != True:
return ""
eventId = tmp[1].split('\n')[0].strip()
sql = "select objectid from events where eventid=%s" % (eventId)
db = MySQLdb.connect(mysql_server, mysql_user, mysql_pass, db_name)
cursor = db.cursor()
print(sql)
cursor.execute(sql)
results = cursor.fetchall()
if any(results):
db.close()
return str(results[0][0]), str(eventId)
return "", ""
# 通过ITEM ID查询图表
def getGraphId(body):
# 获得ITEM ID
itemId = body.split("ITEM ID: ")[1]
db = MySQLdb.connect(mysql_server, mysql_user, mysql_pass, db_name)
cursor = db.cursor()
sql = "select graphs_items.graphid, graphs.graphtype from graphs_items,graphs where graphs_items.itemid=%s and graphs_items.graphid = graphs.graphid limit 1;" % (itemId)
cursor.execute(sql)
results = cursor.fetchall()
# 存在关联的图表
if any(results):
db.close()
return int(results[0][0]), results[0][1], 1
# 不存在关联图表
return int(itemId), 0, 0
def main(to, subject, body):
itemId = int(body.split("ITEM ID: ")[1])
triggerid, eventId = getEvent(body)
if itemId > 0:
graphid, type, flag = getGraphId(body)
os.popen("""mkdir -p %s""" % (image_path))
os.popen("""curl -c '%s' -b '%s' -d "request=&name=%s&password=%s&autologin=1&enter=Sign+in" %s/index.php""" % (cookie, cookie, zabbix_user, zabbix_pass, zabbix_url))
# 存在关联的图表
if flag > 0:
print("存在关联的图表: " + str(graphid))
zabbixUrl = zabbix_url + "/charts.php?graphid=" + str(graphid)
os.popen("""curl -b '%s' -F "graphid=%d" -F "period=%d" -F "stime=%s" -F "width=%d" %s > %s%s.png""" % (cookie, graphid, period, stime, width, zabbix_url + "/chart2.php", image_path, stime))
# 不存在关联图表,仅有独立item
else:
print("不存在关联图表")
zabbixUrl = zabbix_url + "/history.php?action=showgraph&itemids[0]=" + body.split("ITEM ID: ")[1]
os.popen("""curl -b '%s' -F "itemids[0]=%s" -F "period=%d" -F "stime=%s" -F "width=%d" %s > %s%s.png""" % (cookie, graphid, period, stime, width, zabbix_url + "/chart.php", image_path, stime))
# "title_link": zabbix_url + """/tr_events.php?triggerid=%s&eventid=%s""" % (triggerid, eventId),
text = "[" + subject + "](" + zabbixUrl + ")\r\n";
text += "```" + body.strip() + "```";
print(text);
values = {
"chat_id": to,
"photo": image_url + str(stime) + ".png",
#"document": image_url + str(stime) + ".png",
"caption": text,
"parse_mode": 'Markdown',
}
print('image url: ' + image_url + str(stime) + ".png")
return requests.post(servicesUrl, data = values).text, values
# 没有ITEM ID,仅发送信息
values = {"text": subject + "\r\n" + body, "attachments": [{"footer": "Zabbix API", "footer_icon": "https://img.domain.com/zabbix-logo.png"}]}
return requests.post(servicesUrl, data = values).text, values
if __name__ == "__main__":
currTime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
res, values = main(to, subject, body)
txt = u"------------" + currTime + "------------\nto: " + to + " | subject: " + subject + "\nbody: \n" + body + "\n\nresult: " + res + "\n\nvalues: " + json.dumps(values) + "\n\n"
file = codecs.open("/tmp/zabbix_result.txt", "w", "utf-8-sig")
file.write(txt)
file.close()
print(txt)