用python 写一个 登录到zabbix5.0后 自动获取图形 并发送邮件的脚本
时间: 2024-03-13 12:45:48 浏览: 81
好的,这是一个比较复杂的脚本,需要用到zabbix的API、smtplib和email库。以下是基本的脚本框架:
```python
import requests
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
# 邮件发送信息
mail_host = "SMTP服务器地址"
mail_port = "SMTP服务器端口"
mail_user = "发送邮件的邮箱账号"
mail_password = "发送邮件的邮箱密码"
sender = "发送邮件的邮箱账号"
receivers = ["收件人邮箱地址"]
# Zabbix接口信息
zabbix_url = "Zabbix服务器地址"
zabbix_user = "Zabbix登录用户名"
zabbix_password = "Zabbix登录密码"
graph_id = "获取的图形ID"
graph_width = "图形宽度"
graph_height = "图形高度"
graph_period = "图形显示时间周期"
# 登录Zabbix获取API认证令牌
session = requests.Session()
login_url = zabbix_url + "/api_jsonrpc.php"
headers = {"Content-Type": "application/json-rpc"}
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": zabbix_user,
"password": zabbix_password
},
"id": 1
}
response = session.post(login_url, headers=headers, json=data)
auth = response.json()["result"]
# 获取图形并保存
graph_url = zabbix_url + "/chart2.php"
params = {
"graphid": graph_id,
"width": graph_width,
"height": graph_height,
"period": graph_period,
"stime": "now",
"profileIdx": "web.graphs.filter",
"profileIdx2": graph_id
}
response = session.get(graph_url, params=params)
with open("graph.png", "wb") as f:
f.write(response.content)
# 发送邮件
msg = MIMEMultipart()
msg["Subject"] = "Zabbix图形邮件"
msg["From"] = sender
msg["To"] = ",".join(receivers)
text = MIMEText("Zabbix图形邮件")
msg.attach(text)
with open("graph.png", "rb") as f:
image = MIMEImage(f.read())
msg.attach(image)
smtp_obj = smtplib.SMTP(mail_host, mail_port)
smtp_obj.login(mail_user, mail_password)
smtp_obj.sendmail(sender, receivers, msg.as_string())
smtp_obj.quit()
```
需要注意的是,需要替换脚本中的邮件发送信息、Zabbix接口信息和图形ID等参数。另外,图形保存的文件名为"graph.png",如果需要可以自行修改。
阅读全文