zabbix python add host py

沒有該主機組的時候要先添加主機組:./python_zabbix_host.py -A yourname

vi python_zabbix_host.py

!/usr/bin/python

coding:utf-8

import json
import urllib2
from urllib2 import URLError
import sys, argparse
import xlrd
import socket
import os

os.chdir('/usr/local/src')
os.system('yum install -y unzip')
if os.path.exists('setuptools-38.2.4') == False:
os.system(
'wget https://pypi.python.org/packages/69/56/f0f52281b5175e3d9ca8623dadbc3b684e66350ea9e0006736194b265e99/setuptools-38.2.4.zip#md5=e8e05d4f8162c9341e1089c80f742f64 --no-check-certificate')
os.system('unzip setuptools-38.2.4.zip')
os.chdir('/usr/local/src/setuptools-38.2.4')
os.system('python setup.py build')
os.system('python setup.py install')
os.chdir('/usr/local/src')
if os.path.exists('pip-9.0.1') == False:
os.system(
'wget --no-check-certificate https://pypi.python.org/packages/11/b6/abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/pip-9.0.1.tar.gz#md5=35f01da33009719497f01a4ba69d63c9')
os.system('tar -xzvf pip-9.0.1.tar.gz')
os.chdir('/usr/local/src/pip-9.0.1')
os.system('python setup.py build')
os.system('python setup.py install')
os.system('pip install xlrd')
else:
os.chdir('/usr/local/src/pip-9.0.1')
os.system('pip install xlrd')

defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
reload(sys)
sys.setdefaultencoding(defaultencoding)

def get_host_ip():
"""
查詢本機ip地址
:return: ip
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()

return ip

a = get_host_ip()

class zabbix_api:
def init(self):
self.url = 'http://' + a + '/zabbix/api_jsonrpc.php' # 修改URL
self.header = {"Content-Type": "application/json"}

def user_login(self):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": "admin",  # web頁面登錄用戶名
            "password": "zabbix"  # web頁面登錄密碼
        },
        "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 "\033[041m 用戶認證失敗湿硝,請檢查 !\033[0m", e.code
    else:
        response = json.loads(result.read())
        result.close()
        # print response['result']
        self.authID = response['result']
        return self.authID

def host_get(self, hostName=''):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": "extend",
            "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())
        # print response
        result.close()
        print "主機數(shù)量: \033[31m%s\033[0m" % (len(response['result']))
        for host in response['result']:
            status = {"0": "OK", "1": "Disabled"}
            available = {"0": "Unknown", "1": "available", "2": "Unavailable"}
            # print host
            if len(hostName) == 0:
                print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m" % (
                host['hostid'], host['name'], status[host['status']], available[host['available']])
            else:
                print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m" % (
                host['hostid'], host['name'], status[host['status']], available[host['available']])
                return host['hostid']

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:
        # print result.read()
        response = json.loads(result.read())
        result.close()
        # print response()
        for group in response['result']:
            if len(hostgroupName) == 0:
                print "hostgroup:  \033[31m%s\033[0m \tgroupid : %s" % (group['name'], group['groupid'])
            else:
                print "hostgroup:  \033[31m%s\033[0m\tgroupid : %s" % (group['name'], group['groupid'])
                self.hostgroupID = group['groupid']
                return group['groupid']

def template_get(self, templateName=''):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": "extend",
            "filter": {
                "name": 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()
        # print response
        for template in response['result']:
            if len(templateName) == 0:
                print "template : \033[31m%s\033[0m\t  id : %s" % (template['name'], template['templateid'])
            else:
                self.templateID = response['result'][0]['templateid']
                print "Template Name :  \033[31m%s\033[0m " % templateName
                return response['result'][0]['templateid']

def hostgroup_create(self, hostgroupName):

    if self.hostgroup_get(hostgroupName):
        print "hostgroup  \033[42m%s\033[0m is exist !" % hostgroupName
        sys.exit(1)
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "hostgroup.create",
        "params": {
            "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()
        print "\033[042m 添加主機組:%s\033[0m  hostgroupID : %s" % (hostgroupName, response['result']['groupids'])

def host_create_andy(self, hostName, visibleName, hostip, hostgroupName, templateName):
    if self.host_get(hostip):
        print "\033[041m該主機已經(jīng)添加!\033[0m"
        sys.exit(1)

    group_list = []
    template_list = []
    for i in hostgroupName.split(','):
        var = {}
        var['groupid'] = self.hostgroup_get(i)
        group_list.append(var)
    for i in templateName.split(','):
        var = {}
        var['templateid'] = self.template_get(i)
        template_list.append(var)

    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostName,
            "name": visibleName,
            "interfaces": [
                {
                    "type": 1,  # 1:表示IP程梦;2表示SNMP
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": "10050"  # IP端口10050稽穆;SNMP端口161
                }
            ],
            "groups": group_list,
            "templates": template_list,
        },
        "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())
        print "添加主機 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])
        result.close()

def host_create(self, hostip, hostgroupName, templateName):
    if self.host_get(hostip):
        print "\033[041m該主機已經(jīng)添加!\033[0m"
        sys.exit(1)

    group_list = []
    template_list = []
    for i in hostgroupName.split(','):
        var = {}
        var['groupid'] = self.hostgroup_get(i)
        group_list.append(var)
    for i in templateName.split(','):
        var = {}
        var['templateid'] = self.template_get(i)
        template_list.append(var)

    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostip,
            "interfaces": [
                {
                    "type": 2,
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": "161"
                }
            ],
            "groups": group_list,
            "templates": template_list,
        },
        "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 "添加主機 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])

def host_disable(self, hostip):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.update",
        "params": {
            "hostid": self.host_get(hostip),
            "status": 1
        },
        "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 '----主機現(xiàn)在狀態(tài)------------'
        print self.host_get(hostip)

def host_delete(self, hostid):
    hostid_list = []
    # print type(hostid)
    for i in hostid.split(','):
        var = {}
        var['hostid'] = self.host_get(i)
        hostid_list.append(var)
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.delete",
        "params": hostid_list,
        "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 Exception, e:
        print  e
    else:

        result.close()
        print "主機 \033[041m %s\033[0m  已經(jīng)刪除 !" % hostid

if name == "main":
zabbix = zabbix_api()
parser = argparse.ArgumentParser(description='zabbix api ', usage='%(prog)s [options]')
parser.add_argument('-H', '--host', nargs='?', dest='listhost', default='host', help='查詢主機')
parser.add_argument('-G', '--group', nargs='?', dest='listgroup', default='group', help='查詢主機組')
parser.add_argument('-T', '--template', nargs='?', dest='listtemp', default='template', help='查詢模板信息')
parser.add_argument('-A', '--add-group', nargs=1, dest='addgroup', help='添加主機組')
parser.add_argument('-C', '--add-host', dest='addhost', nargs=3,
metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'), help='添加主機,多個主機組或模板使用分號')
parser.add_argument('-d', '--disable', dest='disablehost', nargs=1, metavar=('192.168.2.1'), help='禁用主機')
parser.add_argument('-L', '--allin', dest='allin', nargs='?', default='allin', help='從Excel批量導(dǎo)入主機')
parser.add_argument('-D', '--delete', dest='deletehost', nargs='+', metavar=('192.168.2.1'), help='刪除主機,多個主機之間用分號')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
if len(sys.argv) == 1:
print parser.print_help()
else:
args = parser.parse_args()

    if args.listhost != 'host':
        if args.listhost:
            zabbix.host_get(args.listhost)
        else:
            zabbix.host_get()
    if args.listgroup != 'group':
        if args.listgroup:
            zabbix.hostgroup_get(args.listgroup)
        else:
            zabbix.hostgroup_get()
    if args.listtemp != 'template':
        if args.listtemp:
            zabbix.template_get(args.listtemp)
        else:
            zabbix.template_get()
    if args.addgroup:
        zabbix.hostgroup_create(args.addgroup[0])
    if args.addhost:
        zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2])
    if args.disablehost:
        zabbix.host_disable(args.disablehost)
    if args.deletehost:
        zabbix.host_delete(args.deletehost[0])
    if args.allin != 'allin':
        workbook = xlrd.open_workbook('zabbix_host_add.xlsx')  # Excel名钉嘹,表格列 主機名笔呀、顯示名埠帕、IP媳瞪、主機組抑片、模板
        for row in xrange(workbook.sheets()[0].nrows):
            hostname = workbook.sheets()[0].cell(row, 0).value
            visible = workbook.sheets()[0].cell(row, 1).value
            hostip = workbook.sheets()[0].cell(row, 2).value
            hostgroup = workbook.sheets()[0].cell(row, 3).value
            hosttemp = workbook.sheets()[0].cell(row, 4).value

            zabbix.host_create_andy(hostname, visible, hostip, hostgroup, hosttemp)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末睹栖,一起剝皮案震驚了整個濱河市硫惕,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌野来,老刑警劉巖恼除,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異曼氛,居然都是意外死亡豁辉,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進店門舀患,熙熙樓的掌柜王于貴愁眉苦臉地迎上來徽级,“玉大人,你說我怎么就攤上這事聊浅〔颓溃” “怎么了现使?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長旷痕。 經(jīng)常有香客問我碳锈,道長,這世上最難降的妖魔是什么欺抗? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任售碳,我火速辦了婚禮,結(jié)果婚禮上绞呈,老公的妹妹穿的比我還像新娘贸人。我一直安慰自己,他們只是感情好报强,可當(dāng)我...
    茶點故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布灸姊。 她就那樣靜靜地躺著拱燃,像睡著了一般秉溉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上碗誉,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天召嘶,我揣著相機與錄音,去河邊找鬼哮缺。 笑死弄跌,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的尝苇。 我是一名探鬼主播铛只,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼糠溜!你這毒婦竟也來了淳玩?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤非竿,失蹤者是張志新(化名)和其女友劉穎蜕着,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體红柱,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡承匣,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了锤悄。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片韧骗。...
    茶點故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖零聚,靈堂內(nèi)的尸體忽然破棺而出宽闲,到底是詐尸還是另有隱情众眨,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布容诬,位于F島的核電站娩梨,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏览徒。R本人自食惡果不足惜狈定,卻給世界環(huán)境...
    茶點故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望习蓬。 院中可真熱鬧纽什,春花似錦、人聲如沸躲叼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽枫慷。三九已至让蕾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間或听,已是汗流浹背探孝。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留誉裆,地道東北人顿颅。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像足丢,于是被迫代替她去往敵國和親粱腻。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,941評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)載:https://www.cnblogs.com/momoshouhu/p/8053907.html1.安裝x...
    SkTj閱讀 1,607評論 0 1
  • 一斩跌、Python簡介和環(huán)境搭建以及pip的安裝 4課時實驗課主要內(nèi)容 【Python簡介】: Python 是一個...
    _小老虎_閱讀 5,746評論 0 10
  • 推開門 我們走出去那一刻 我沒有說話 我們沒有說話 我沒有穿襪子 我也沒有挽起褲腳 濕漉漉的發(fā)梢 我隨意的用帽子遮...
    陰陽先生閱讀 121評論 0 0
  • 今天看了jieba庫
    4e7a0fcb4de6閱讀 93評論 0 1
  • 今天下了一整天的雨了 而且一點都沒有要停的感覺 站在公司門口透氣 玻璃棚頂在微微的漏水 一下滴身上 那股寒冷和風(fēng)的...
    wousainty閱讀 151評論 0 0