zabbix api example
- #!/usr/bin/env python
- #coding=utf-8
- import json,urllib2
- #url and url header
- zabbix_url="http://zabbix.test.org/api_jsonrpc.php"
- zabbix_header = {"Content-Type":"application/json"}
- zabbix_user = "admin"
- zabbix_pass = "123456"
- #auth user adn password
- auth_data = json.dumps(
- {
- "jsonrpc":"2.0",
- "method":"user.login",
- "params": {
- "user":zabbix_user,
- "password":zabbix_pass
- },
- "id":0
- })
- # create request object
- request = urllib2.Request(zabbix_url,auth_data)
- for key in zabbix_header:
- request.add_header(key,zabbix_header[key])
- #auth and get authid
- try:
- result = urllib2.urlopen(request)
- except URLError as e:
- print "认证失败,请检查用户名和密码是否正确",e.code
- else:
- response=json.loads(result.read())
- result.close()
- auth_code=response['result']
- # request json
- get_host_data = json.dumps(
- {
- "jsonrpc":"2.0",
- "method":"host.get",
- "params":{
- "output":["hostid","name","available","maintenance_status","status","error"],
- #"filter":{"host":""}
- },
- #auth string
- "auth":auth_code,
- "id":1,
- })
- # create request object
- request = urllib2.Request(zabbix_url,get_host_data)
- for key in zabbix_header:
- request.add_header(key,zabbix_header[key])
- # get host list
- try:
- result = urllib2.urlopen(request)
- except URLError as e:
- if hasattr(e, 'reason'):
- print 'We failed to reach a server.'
- print 'Reason: ', e.reason
- elif hasattr(e, 'code'):
- print 'The server could not fulfill the request.'
- print 'Error code: ', e.code
- else:
- response = json.loads(result.read())
- result.close()
- print "Number Of Hosts: ", len(response['result'])
- for host in response['result']:
- print "Host ID:",host['hostid'],"Host Name:",host['name'],"Status",host['status']
本文转自it你好 51CTO博客,原文链接:http://blog.51cto.com/itnihao/1178902,如需转载请自行联系原作者