zabbix批量添加主機-學(xué)習(xí)實踐

依據(jù)網(wǎng)上大神提供的解決方案進(jìn)行了一次zabbix批量添加主機的實踐,發(fā)現(xiàn)這種方式也可算是另類的“自動化”,雖然還需要手動執(zhí)行,但最終還是減少了大部分工作量,提高了生產(chǎn)力。

方案參考:

http://blog.51cto.com/net881004/2089104

系統(tǒng)與環(huán)境準(zhǔn)備

Ubuntu18.04

python2.7環(huán)境

1.安裝python的xlrd包(用于支持讀取excel文件)

官網(wǎng)下載xlrd模塊

https://pypi.python.org/pypi/xlrd

#使用pypi安裝模塊,需先安裝pypi包
apt-get install pypi
#安裝xlrd
pip install xlrd

2.批量添加腳本

#來源于參考鏈接
#json中的相關(guān)方法對象,直接在zabbix官方網(wǎng)站上獲取
##############################################################################################

#!/usr/local/kk-mail/app/engine/bin/python

#coding:utf-8

import json 

import urllib2 

from urllib2 import URLError 

import sys 

import xlrd

class ZabbixTools: 

    def __init__(self): 

        self.url = 'http://10.x.x.x/zabbix/api_jsonrpc.php'  #zabbix的api接口

        self.header = {"Content-Type":"application/json"} 

    def user_login(self): 

        data = json.dumps({ 

                           "jsonrpc": "2.0", 

                           "method": "user.login", 

                           "params": { 

                                      "user": "Admin",  #web登錄zabbix的管理員賬號或有權(quán)限賬號

                                      "password": "zabbix" 

                                      }, 

                           "id": 0 

                           }) 

        request = urllib2.Request(self.url, data) 

        for key in self.header: 

            request.add_header(key, self.header[key]) 

        try: 

            result = urllib2.urlopen(request) 

        except URLError as e: 

            print "Auth Failed, please Check your name and password:", e.code 

        else: 

            response = json.loads(result.read()) 

            result.close() 

            self.authID = response['result'] 

            return self.authID 

    def host_get(self,hostName): 

        data = json.dumps({ 

                           "jsonrpc":"2.0", 

                           "method":"host.get", 

                           "params":{ 

                                     "output":["hostid","name"], 

                                     "filter":{"host":hostName} 

                                     }, 

                           "auth":self.user_login(), 

                           "id":1, 

                           }) 

        request = urllib2.Request(self.url, data) 

        for key in self.header: 

            request.add_header(key, self.header[key]) 

        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 %s: " % hostName, len(response['result']) 

            lens=len(response['result']) 

            if lens > 0:

                return response['result'][0]['name']

            else:

                return ""

    def hostgroup_get(self, hostgroupName): 

        data = json.dumps({ 

                           "jsonrpc":"2.0", 

                           "method":"hostgroup.get", 

                           "params":{ 

                                     "output": "extend", 

                                     "filter": { 

                                                "name": [ 

                                                         hostgroupName, 

                                                         ] 

                                                } 

                                     }, 

                           "auth":self.user_login(), 

                           "id":1, 

                           }) 

        request = urllib2.Request(self.url, data) 

        for key in self.header: 

            request.add_header(key, self.header[key]) 

        try: 

            result = urllib2.urlopen(request) 

        except URLError as e: 

            print "Error as ", e 

        else: 

            response = json.loads(result.read()) 

            result.close() 

            lens=len(response['result']) 

            if lens > 0:

                self.hostgroupID = response['result'][0]['groupid']

                return response['result'][0]['groupid']

            else:

                print "no GroupGet result"

                return ""

    def template_get(self, templateName): 

        data = json.dumps({ 

                           "jsonrpc":"2.0", 

                           "method": "template.get", 

                           "params": { 

                                      "output": "extend", 

                                      "filter": { 

                                                 "host": [ 

                                                          templateName, 

                                                          ] 

                                                 } 

                                      }, 

                           "auth":self.user_login(), 

                           "id":1, 

                           }) 

        request = urllib2.Request(self.url, data) 

        for key in self.header: 

            request.add_header(key, self.header[key]) 

        try: 

            result = urllib2.urlopen(request) 

        except URLError as e: 

            print "Error as ", e 

        else: 

            response = json.loads(result.read()) 

            result.close() 

            self.templateID = response['result'][0]['templateid'] 

            return response['result'][0]['templateid'] 

    def host_create(self, hostName,visibleName,dnsName, hostgroupName, templateName1,ip): 

        data = json.dumps({ 

                           "jsonrpc":"2.0", 

                           "method":"host.create", 

                           "params":{ 

                                     "host": hostName, 

                                     "name": visibleName, 

                                     "interfaces": [ 

                                                        { 

                                                            "type": 2, 

                                                            "main": 1, 

                                                            "useip": 0, 

                                                            "ip": ip, 

                                                            "dns": dnsName, 

                                                            "port": "161" 

                                                        } 

                                                    ], 

                                    "groups": [ 

                                                    { 

                                                        "groupid": self.hostgroup_get(hostgroupName) 

                                                    } 

                                               ], 

                                    "templates": [ 

                                                    { 

                                                        "templateid": self.template_get(templateName1)

                                                    }

                                                  ], 

                                     }, 

                           "auth": self.user_login(), 

                           "id":1                   

        }) 

        request = urllib2.Request(self.url, data) 

        for key in self.header: 

            request.add_header(key, self.header[key]) 

        try: 

            result = urllib2.urlopen(request) 

        except URLError as e: 

            print "Error as ", e 

        else: 

            response = json.loads(result.read()) 

            result.close() 

            print "host : %s is created!   id is  %s\n" % (dnsname, response['result']['hostids'][0]) 

            self.hostid = response['result']['hostids'] 

            return response['result']['hostids'] 

    def proxy_get(self, ProxyName):

        data = json.dumps({

                           "jsonrpc":"2.0",

                           "method": "proxy.get",

                           "params": {

                                      "output": "extend",

                                      "selectInterface": "extend",

                                      "filter": {

                                          "host": [ ProxyName, ]

                                      }

                                      },

                           "auth":self.user_login(),

                           "id":1,

                           })

        request = urllib2.Request(self.url, data)

        for key in self.header:

            request.add_header(key, self.header[key])

        try:

            result = urllib2.urlopen(request)

        except URLError as e:

            print "Error as ", e

        else:

            response = json.loads(result.read())

            result.close()

            self.templateID = response['result'][0]['proxyid']

            return response['result'][0]['proxyid']

if __name__ == "__main__": 

    test = ZabbixTools() 

    workbook = xlrd.open_workbook('zabbixauto.xlsx')  #讀取文件名為“zabbixauto.xlsx”的表格文件

    for row in xrange(workbook.sheets()[0].nrows): #excel文件包含以下6列

        hostname=workbook.sheets()[0].cell(row,0).value

        visible=workbook.sheets()[0].cell(row,1).value

        dnsname=workbook.sheets()[0].cell(row,2).value

        hostgroup=workbook.sheets()[0].cell(row,3).value

        hosttemp=workbook.sheets()[0].cell(row,4).value

        ip=workbook.sheets()[0].cell(row,5).value

        hostgroup=hostgroup.strip()

        hostnameGet=test.host_get(hostname)

        if hostnameGet.strip()=='':

            test.host_create(hostname,visible,dnsname,hostgroup,hosttemp,ip)

        else:

            print "%s have exist! Cannot recreate !\n" % hostnameGet                                             

3.編輯excel

excel文件中的每列對應(yīng),在zabbix上創(chuàng)建主機時的相關(guān)設(shè)置

第一列 Host name

第二列 Visible name

第三列 dns name

第四列 hostgroup

第五列 ip
image

4.腳本執(zhí)行

實際批量添加時,將excel文件和批量腳本放到同一個目錄下,填寫好excel后,直接執(zhí)行腳本即可

root@zabbix:/home/admin# ls -l

total 11484

-rwxrwxr-x 1 admin admin   10067 Mar 11 07:32 zabbixauto-host.py

-rw-rw-r-- 1 admin admin    9696 Mar 11 07:27 zabbixauto.xlsx

5.驗證

image
image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)載:https://www.cnblogs.com/momoshouhu/p/8053907.html1.安裝x...
    SkTj閱讀 1,780評論 0 1
  • Zabbix簡介 Zabbix官方網(wǎng)站Zabbix中文文檔 本文系統(tǒng)環(huán)境是CentOS7x86_64, Zabbi...
    Zhang21閱讀 8,288評論 0 37
  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個 Awesome - XXX 系列...
    小邁克閱讀 3,122評論 1 3
  • 一、架構(gòu)設(shè)計及環(huán)境規(guī)劃: 架構(gòu)設(shè)計圖: 架構(gòu)設(shè)計說明: 1. 基礎(chǔ)架構(gòu)為LAMP環(huán)境,采用keepalived實現(xiàn)...
    Bogon閱讀 10,826評論 1 10
  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時實驗課主要內(nèi)容 【Python簡介】: Python 是一個...
    _小老虎_閱讀 6,313評論 0 10

友情鏈接更多精彩內(nèi)容