1. 程式人生 > >zabbix:利用zabbix api獲取指定組中的主機的名字並將其修改

zabbix:利用zabbix api獲取指定組中的主機的名字並將其修改

思路講解:首先利用hostgroup.get方法獲取zabbix組的id與名字,然後檢索獲得指定組的id,再利用host.get獲取該指定組下的所有主機的id與名字,最後利用host.update根據主機的id更新主機的名字。
程式碼如下:

#!/usr/bin/env python 
#coding=utf-8 
 
#匯入模組,urllib2是一個模擬瀏覽器HTTP方法的模組
import json
import urllib2
import sys
from urllib2 import Request, urlopen, URLError, HTTPError
 
#url and url header 
#zabbix的api 地址,使用者名稱,密碼,這裡修改為自己實際的引數
zabbix_url="http://10.10.30.232/zabbix/api_jsonrpc.php" 
zabbix_header = {"Content-Type":"application/json"} 
zabbix_user   = "admin" 
zabbix_pass   = "zabbix" 
auth_code     = ""
#prefix='SSCC-'

#auth user and password 
#使用者認證資訊的部分,最終的目的是得到一個SESSIONID
#這裡是生成一個json格式的資料,使用者名稱和密碼

def get_auth_id():
    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 HTTPError, e:
        print 'The server couldn\'t fulfill the request, Error code: ', e.code
    except URLError, e:
        print 'We failed to reach a server.Reason: ', e.reason
    else: 
        response=json.loads(result.read()) 
        result.close() 
        #判斷SESSIONID是否在返回的資料中
        if  'result'  in  response:
            auth_code=response['result']
            return auth_code
        else:
            print  response['error']['data']
            return 0


def get_groupid_name(auth_code, group_name):
    # request json 
    json_data={ 
            "method":"hostgroup.get", 
            "params":{
                    "output": ["groupid","name"],
            }
        }
    json_base={
        "jsonrpc":"2.0",
        "auth":auth_code,
        "id":1
    }
    json_data.update(json_base)
    #用得到的SESSIONID去通過驗證,獲取主機的資訊(用http.get方法)
    if len(auth_code) == 0:
        sys.exit(1)
    if len(auth_code) != 0:
        get_host_data = json.dumps(json_data) 
    
        # create request object 
        request = urllib2.Request(zabbix_url,get_host_data) 
        for key in zabbix_header: 
            request.add_header(key,zabbix_header[key]) 
    
        # get group 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(json.dumps(response,indent=4))

            for i in range(len(response['result'])):
                if response['result'][i]['name'] == group_name:
                    return response['result'][i]['groupid']
            return -1

def get_host_list(auth_code, group_id):
    # request json 
    json_data={ 
            "method":"host.get", 
            "params":{
                    "groupids": group_id,
                    "output": ["name"],
            }
        }
    json_base={
        "jsonrpc":"2.0",
        "auth":auth_code,
        "id":1
    }
    json_data.update(json_base)
    #用得到的SESSIONID去通過驗證,獲取主機的資訊(用http.get方法)
    if len(auth_code) == 0:
        sys.exit(1)
    if len(auth_code) != 0:
        get_host_data = json.dumps(json_data) 
    
        # 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 json.dumps(response,indent=4)
            #顯示主機的個數
            #print "Number Of Hosts: ", len(response['result'])
            return response['result']

def get_host_update(auth_code, hostid, name):
    json_data={ 
            "method":"host.update", 
            "params":{
                    "hostid":hostid,
                    "name": name,
            }
        }
    json_base={
        "jsonrpc":"2.0",
        "auth":auth_code,
        "id":1
    }
    json_data.update(json_base)

    if len(auth_code) == 0:
        sys.exit(1)
    if len(auth_code) != 0:
        get_update_data = json.dumps(json_data) 
    
        # create request object 
        request = urllib2.Request(zabbix_url,get_update_data) 
        for key in zabbix_header: 
            request.add_header(key,zabbix_header[key]) 
    
        # get update 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 json.dumps(response,indent=4)


def main():
    group_name = sys.argv[1]
    prefix = sys.argv[2]
    auth_code = get_auth_id()
    group_id = get_groupid_name(auth_code,group_name)
    #print( group_id )
    hostid_name=get_host_list(auth_code, group_id)
    for i in range(len(hostid_name)):
        hostid = hostid_name[i]['hostid']
        name = prefix + hostid_name[i]['name']
        get_host_update(auth_code, hostid, name)


if __name__=='__main__':
    main()