python 通用调用zabbix的api

       

  1. #!/usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3.   
  4. import re  
  5. import sys  
  6. import json  
  7. import urllib  
  8. import urllib2  
  9.    
  10. class zabbixtools:  
  11.    
  12.     def __init__(self, hostip, hostname):  
  13.         self.url = "http://8.8.8.8/zabbix/api_jsonrpc.php"  
  14.         self.header = {"Content-Type""application/json"}  
  15.         self.authID = self.user_login()  
  16.         self.hostip = hostip.strip("\n")  
  17.         self.hostname = hostname.strip("\n")  
  18.       
  19.     def user_login(self):  
  20.         data = json.dumps(  
  21.             {  
  22.                 "jsonrpc""2.0",  
  23.                 "method""user.login",  
  24.                 "params": {  
  25.                     "user""zabbix",  
  26.                     "password""zabbix"  
  27.                     },  
  28.                 "id"0  
  29.                 })  
  30.    
  31.         request = urllib2.Request(self.url,data)  
  32.         for key in self.header:  
  33.             request.add_header(key,self.header[key])  
  34.         try:  
  35.             result = urllib2.urlopen(request)  
  36.         except URLError as e:  
  37.             print "Auth Failed, Please Check Your Name And Password:"  
  38.         else:  
  39.             response = json.loads(result.read())  
  40.             result.close()  
  41.             authID = response['result']  
  42.             return authID  
  43.    
  44.     def get_data(self,data,hostip=""):  
  45.         request = urllib2.Request(self.url,data)  
  46.         for key in self.header:  
  47.             request.add_header(key,self.header[key])  
  48.         try:  
  49.             result = urllib2.urlopen(request)  
  50.         except Exception,e:  
  51.             if hasattr(e,'reason'):  
  52.                 print "we Failed to reach a server"  
  53.                 print 'reason:',e.reason  
  54.             elif hasattr(e,'code'):  
  55.                 print "the server could not fulfaild the request"  
  56.                 print "error code:",e.code  
  57.             return 0  
  58.         else:  
  59.             response = json.loads(result.read())  
  60.             result.close()  
  61.             return response  
  62.    
  63.    
  64.     def host_get(self):  
  65.         # 生成json格式数据  
  66.         data = json.dumps(  
  67.             {  
  68.                 "jsonrpc""2.0",  
  69.                     "method""host.get",  
  70.                     "params": {  
  71.                         "output":["hostid","name","status","host"],  
  72.                         "filter": {"host": [self.hostip]}  
  73.                         },  
  74.                     "auth"self.authID,  
  75.                     "id"1  
  76.             })  
  77.         res = self.get_data(data)['result']  
  78.         if (res != 0and (len(res) != 0):  
  79.             host = res[0]  
  80.             return   host['hostid']  
  81.         else:  
  82.             print "host_get error please check define host_get()"  
  83.             return 0  
  84.    
  85.     def host_update(self):  
  86.         host = self.host_get()  
  87.         data = json.dumps(  
  88.             {  
  89.                  "jsonrpc""2.0",  
  90.                  "method""host.update",  
  91.                  "params": {  
  92.                          "hostid": host,  
  93.                          "name"self.hostname.encode('utf8')  
  94.                         },  
  95.                  "auth"self.authID,  
  96.                  "id"1  
  97.                  })  
  98.         res = self.get_data(data)   
  99.         
  100.               
  101. def hostname(IP):  
  102.     url = 'http://www.baidu.com/restful/getAssetByIpAddress'   
  103.     user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'   
  104.     values = {'ipAddress': IP}   
  105.     headers = {'User-Agent': user_agent}   
  106.     data = urllib.urlencode(values)   
  107.     req = urllib2.Request(url, data, headers)   
  108.     response = urllib2.urlopen(req)   
  109.     res = response.read()   
  110.     a = json.loads(res)   
  111.     #lable = a['returnedInfo']  
  112.     if a:  
  113.         lable = a[0]  
  114.         if len(lable):  
  115.             #leader = a['returnedInfo'][0]['productLeader']  
  116.             leader = a[0]['productLeader']  
  117.             jif = a[0]['cloudSource']  
  118.             #product = a['returnedInfo'][0]['productName']  
  119.             product = a[0]['productName']  
  120.             #os = a['returnedInfo'][0]['osInfo'][0:7]  
  121.        #     os = a[0]['osInfo'][0:7]  
  122.             #owner = a['returnedInfo'][0]['productOwner']  
  123.             owner = a[0]['productOwner']  
  124.             HOSTNAME = "%s_%s_%s_%s_%s" % (IP, u"", product, u"", u"")  
  125.             return  HOSTNAME  
  126.         else:  
  127.             return 0  
  128.     else:  
  129.         print IP  
  130.    
  131.    
  132. if __name__ == "__main__":   
  133.     for line in open("hosts.log"):  
  134.         host = re.findall(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line)  
  135.         IP = host[0]  
  136.         print IP  
  137.         b = hostname(IP)  
  138.         if  b:  
  139.             update = zabbixtools(line,b)  
  140.             update.host_update()  
  141.         else:  
  142.             print b  

猜你喜欢

转载自hugoren.iteye.com/blog/2298369