python 调用 zabbixApi

2015/08/28 12:17
阅读数 42
#!/usr/bin/env python
import json
import urllib2

class ZabbixApi:
    def __init__(self,api_info):
        self.api_info = api_info
        self.header = {"Content-Type": "application/json"}
        self.api_data = {
                'jsonrpc':'2.0',
                'method':'',
                'params':'',
                'id':0
                }
        self._set_auth_session()
        
    def _set_auth_session(self):
        self.api_data['method'] = 'user.login'
        self.api_data['params']= {
                          'user':self.api_info['user'],
                          'password':self.api_info['password']
                        }
        response = self._request()
        self.api_data['auth'] = response['result']
        self.api_data['id'] = 1
        
    def _request(self):
        post_data = json.dumps(self.api_data)
        req = urllib2.Request(self.api_info['url'],post_data)
        for k,v in self.header.items():
            req.add_header(k,v)
        
        try:
            result = urllib2.urlopen(req)
        except urllib2.URLError as e:
            print e.code
        else:
            response = json.loads(result.read())
            result.close()
            return response
        
    def get_data(self,method,params):
        self.api_data['method'] = method
        self.api_data['params']= params
        return self._request()

if __name__ == "__main__":
    api_info = {
            'url': 'http://site/api_jsonrpc.php',
            'user':'user',
            'password':'password'
    }
    zbx = ZabbixApi(api_info)
   
    #获取主机列表
    print zbx.get_data("host.get",{'output':"extend"})
    
    #获取Group列表
    print zbx.get_data("hostgroup.get",{'output':"extend"})


展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部