运维网

 找回密码
 
查看: 687|回复: 0

zabbix api example

[复制链接]
zabbix  api  example

    [Shell] 纯文本查看 复制代码
    1. #!/usr/bin/env python
    2. #coding=utf-8

    3. import json,urllib2

    4. #url and url header
    5. zabbix_url="http://zabbix.test.org/api_jsonrpc.php"
    6. zabbix_header = {"Content-Type":"application/json"}
    7. zabbix_user  =  "admin"
    8. zabbix_pass  =  "123456"

    9. #auth user adn password
    10. auth_data = json.dumps(
    11. {
    12.     "jsonrpc":"2.0",
    13.     "method":"user.login",
    14.     "params": {
    15.     "user":zabbix_user,
    16.     "password":zabbix_pass
    17.     },
    18. "id":0
    19. })

    20. # create request object
    21. request = urllib2.Request(zabbix_url,auth_data)
    22. for key in zabbix_header:
    23.     request.add_header(key,zabbix_header[key])

    24. #auth and get authid
    25. try:
    26.     result = urllib2.urlopen(request)
    27. except URLError as e:
    28.     print "认证失败,请检查用户名和密码是否正确",e.code
    29. else:
    30.     response=json.loads(result.read())
    31.     result.close()
    32.     auth_code=response['result']




    33. # request json
    34. get_host_data = json.dumps(
    35. {
    36.     "jsonrpc":"2.0",
    37.     "method":"host.get",
    38.     "params":{
    39.         "output":["hostid","name","available","maintenance_status","status","error"],
    40.         #"filter":{"host":""}
    41.     },
    42.     #auth string
    43.     "auth":auth_code,  
    44.     "id":1,
    45. })
    46.   
    47. # create request object
    48. request = urllib2.Request(zabbix_url,get_host_data)
    49. for key in zabbix_header:
    50.     request.add_header(key,zabbix_header[key])
    51.   
    52. # get host list
    53. try:
    54.     result = urllib2.urlopen(request)
    55. except URLError as e:
    56.     if hasattr(e, 'reason'):
    57.         print 'We failed to reach a server.'
    58.         print 'Reason: ', e.reason
    59.     elif hasattr(e, 'code'):
    60.         print 'The server could not fulfill the request.'
    61.         print 'Error code: ', e.code
    62. else:
    63.     response = json.loads(result.read())
    64.     result.close()
    65.   
    66.     print "Number Of Hosts: ", len(response['result'])
    67.      
    68.     for host in response['result']:
    69.         print "Host ID:",host['hostid'],"Host Name:",host['name'],"Status",host['status']
    复制代码

GMT,

Powered by Discuz!

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表