示例:調(diào)用 Zabbix API 取得 templateid
- python 函數(shù)實(shí)現(xiàn)
# coding: utf-8
import requests
import json
import uuid
zabbix_url = 'http://192.168.1.254/api_jsonrpc.php'
headers = {"Content-Type": "application/json-rpc"}
data = {
"jsonrpc": "2.0",
"id": str(uuid.uuid1()),
"auth": None
}
def post_action(data):
req = requests.post(zabbix_url, data=json.dumps(data), headers=headers)
dict_data = json.loads(req.text)
return dict_data['result']
def get_user_token(username, password):
data['method'] = "user.login"
data['params'] = {
"user": username,
"password": password
}
return post_action(data)
def zabbix_action(method, params, auth):
data['method'] = method
data['params'] = params
data['auth'] = auth
return post_action(data)
if __name__ == "__main__":
auth = get_user_token('Admin', 'zabbix')
method = "template.get"
params = {
"output": [
"templateid",
],
"filter": {
"host": [
"Template OS Linux",
]
}
}
template_id= zabbix_action(method, params, auth)
print template_id
- python 類實(shí)現(xiàn)
# coding: utf-8
import requests
import json
import uuid
class ZabbixApi(object):
def __init__(self, zabbix_url):
self.zabbix_url = zabbix_url
self.headers = {"Content-Type": "application/json-rpc"}
self.data = {
"jsonrpc": "2.0",
"id": str(uuid.uuid1()),
"auth": None
}
def post_action(self, data):
req = requests.post(self.zabbix_url, data=json.dumps(data), headers=self.headers)
dict_data = json.loads(req.text)
return dict_data['result']
def get_user_token(self, username, password):
self.data['method'] = "user.login"
self.data['params'] = {
"user": username,
"password": password
}
return self.post_action(self.data)
def zabbix_action(self, method, params, auth):
self.data['method'] = method
self.data['params'] = params
self.data['auth'] = auth
return self.post_action(self.data)
if __name__ == "__main__":
url = 'http://192.168.1.254/api_jsonrpc.php'
zabbix_api = ZabbixApi(url)
auth = zabbix_api.get_user_token('Admin', 'zabbix')
method = "template.get"
params = {
"output": "templateid",
"filter": {
"host": [
"Template OS Linux",
]
}
}
template_id = zabbix_api.zabbix_action(method, params, auth)
print template_id