Zabbix API允許以程式化方式與Zabbix進行互動,實現自動化和二次開發,如自動添加主機、更改配置、獲取統計數據等任務,本文將介紹如何在Python環境中設置並運行Zabbix API腳本。
1.安裝套件
#sudo yum -y install gcc openssl-devel bzip2-devel libffi-devel
2.下載Python3.7
#cd /usr/src
#sudo wget https://www.python.org/ftp/python/3.7.12/Python-3.7.12.tgz
#sudo tar xzf Python-3.7.12.tgz
3.確認安裝Python與pip
#python3.7 --version
#pip3.7 --version
有成功顯示版本信息表示安裝成功
4.安裝Python的requests
#pip3.7 install requests
這個問題是我執行腳本時遇到的相容性問題,依據各環境版本做升級或降級,我的作業系統中的預設版本為1.0.2須升級為1.1.1以上才能運行
1.升級OpenSSL
#yum install openssl openssl-devel -y
2.使用virtualenv可以為每個Python專案創建獨立的環境。這避免了套件之間的相容性問題,並能確保專案的套件版本一致性。
#pip install virtualenv
#virtualenv venv
#source venv/bin/activate
#pip install requests
3.如果執行以上還是沒辦法執行腳本的話,可考慮降級urllib3
#pip install urllib3==1.26
1.範例創建一個Demo腳本
#vim zabbix_api_demo.py
2.範例腳本內如如下:
# -*- coding: utf-8 -*-
import requests
import json
ZABBIX_URL ="http://ZabbixIP/zabbix"
ZABBIX_USERNAME = "Zabbix-UserName"
ZABBIX_PASSWORD = "Zabbix-PassWord" #以上三行應替換為登入頁面信息
headers = {
"Content-Type": "application/json-rpc"
}
# 1. 登入Zabbix
login_data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": ZABBIX_USERNAME,
"password": ZABBIX_PASSWORD
},
"id": 1,
"auth": None
}
response = requests.post(ZABBIX_URL + "/api_jsonrpc.php", data=json.dumps(login_data), headers=headers)
auth_token = response.json().get("result")
if auth_token:
print("Successfully logged in!")
# 2. 獲取主機列表
host_data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": ["hostid", "name"],
"selectInterfaces": ["ip"]
},
"id": 2,
"auth": auth_token
}
response = requests.post(ZABBIX_URL + "/api_jsonrpc.php", data=json.dumps(host_data), headers=headers)
hosts = response.json().get("result")
for host in hosts:
print("Host ID: {} | Host Name: {} | IP: {}".format(host['hostid'], host['name'], host['interfaces'][0]['ip']))
# 3. 登出Zabbix
logout_data = {
"jsonrpc": "2.0",
"method": "user.logout",
"params": {},
"id": 3,
"auth": auth_token
}
response = requests.post(ZABBIX_URL + "/api_jsonrpc.php", data=json.dumps(logout_data), headers=headers)
if response.json().get("result"):
print("Successfully logged out!")
else:
print("Failed to login!")
更改添加ZABBIX_URL、ZABBIX_USERNAME、ZABBIX_PASSWORD三行資料後
儲存退出
3.賦予檔案執行權限
#chmod +x zabbix_api_demo.py
4.測試結果
python3.7 zabbix_api_demo.py