Python uses the Zabbix API to add monitoring

Source: Internet
Author: User
Tags addgroup snmp snmp port python script

First of all, the pit is the Python2 and Python3 module change problem, of course, proficient in Python can skip. This Baidu on the internet a bit, the second is to import xlsx files need xlrd module, and this module best follow my method below, that python2 can use my script below.

1. Install xlrd read Excel file

1.1. Download Setuptools-38.2.4.zip, upload to Zabbix server decompression installation,: https://pypi.python.org/packages/69/56/ f0f52281b5175e3d9ca8623dadbc3b684e66350ea9e0006736194b265e99/setuptools-38.2.4.zip#md5= E8e05d4f8162c9341e1089c80f742f64

[email protected] temp]# ll #上传文件setuptools -38.2.4.zip
Total 724
-rw-r--r--1 root root 736683 Dec 22:37 setuptools-38.2.4.zip

[Email protected] temp]# Unzip Setuptools-38.2.4.zip #解压setuptools -38.2.4.zip

1.2 Download pip-9.0.1.tar.gz, upload to Zabbix server decompression installation,: https://pypi.python.org/packages/11/b6/ abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/pip-9.0.1.tar.gz#md5= 35f01da33009719497f01a4ba69d63c9

[email protected] temp]# LL
Total 1896
-rw-r--r--1 root root 1197370 Dec 22:53 pip-9.0.1.tar.gz #上传文件pip -9.0.1.tar.gz
Drwxr-xr-x 9 root root 4096 Dec 22:55 setuptools-38.2.4
-rw-r--r--1 root root 736683 Dec 22:37 setuptools-38.2.4.zip

[Email protected] temp]# TAR-XZVF pip-9.0.1.tar.gz #解压pip -9.0.1.tar.gz

[email protected] pip-9.0.1]# python setup.py build #编译
[email protected] pip-9.0.1]# python setup.py install #安装

[Email protected] pip-9.0.1]# pip install xlrd #安装xlrd

3. Editing Excel templates

3.1 Host name, display name, IP, host group, template

3.2 Uploading the Execle table zabbix_host_add.xlsx to the Zabbix server

[Ro[email protected] temp]# ll
Total 1964
-rw-r--r--1 root root 46079 Dec 23:28 zabbix_host_add.xlsx
4. Write a Python script, refer to http://www.361way.com/zabbix-api-2/3681.html
#!/usr/bin/python
#coding: Utf-8

Import JSON
Import Urllib2
From URLLIB2 import Urlerror
Import Sys,argparse
Import xlrd

defaultencoding = ' Utf-8 '
If sys.getdefaultencoding ()! = defaultencoding:
Reload (SYS)
Sys.setdefaultencoding (defaultencoding)

Class Zabbix_api:
def Init(self):
Self.url = ' Http://zabbix server IP address/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页                           Login user Name "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 user authentication failed, please check!\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 requ            Est. ' Print ' Error code: ', E.code else:response = Json.loads (Result.read ())            #print response Result.close () print "Number of hosts: \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 s Tatus: \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 resp                            Onse () 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 fo R template in response[' result ']: If Len (templatename) ==0:print "Templat E: \033[31m%s\033[0m\t ID:%s "% (template[' name '], template[' TemplateID ']) Else:sel F.templateid = response[' result '][0][' TemplateID '] print "Template Name: \033[31m%s\033[0m"%template Name 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": Hostgroupna                       Me},   "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 Add host Group:%s\033[0m HostGroup ID:%s "% (hostgroupname,response[' result '] [' Groupids ']) def host_create_andy (Self,hostname,visiblename, HostIP, Hostgroupname, templatename): If Self.host_get (hostip): print "\033[041m This host has been added!\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 ({"JSONRP                                     C ":" 2.0 "," Method ":" Host.create "," params ": {                                     "Host": HostName, "name": Visiblename,                                     "Interfaces": [{"Type": 2, #1: Indicates that ip;2 represents SNMP                                     "Main": 1, "Useip": 1, "IP": HostIP, "DNS": "", "Port": "161" #IP                                   Port 10051;SNMP Port 161}],                                     "Groups": Group_list, "Templates": Template_list,                },           "Auth": Self.user_login (), "id": 1}) Request = Urllib            2.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 "Add Host: \033[42m%s\031[0m \tid:         33[31m%s\033[0m "% (HostIP, response[' result '] [' Hostids ']) def host_create (self, hostip, Hostgroupname, templatename):        If Self.host_get (hostip): print "\033[041m the host has been added!\033[0m" sys.exit (1) group_list=[] Template_list=[] for I in Hostgroupname.split (', '): var = {} var[' groupid '] = Self.hos Tgroup_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": {"hos                                     T ": 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 "Add Host: \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 (H            Ostip), "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 ()) Resul T.close () print '----host now status------------' Print Self.host_get (hostip) def Host_del            Ete (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 = Urllib            2.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 "Host \033[041m%s\033[0m has been removed!" %hostid

Ifname== "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= ' query host ')
Parser.add_argument ('-G ', '--group ', nargs= '? ', dest= ' listgroup ', default= ' group ', help= ' query host group ')
Parser.add_argument ('-t ', '--template ', nargs= '? ', dest= ' listtemp ', default= ' template ', help= ' query template information ')
Parser.add_argument ('-A ', '--add-group ', nargs=1,dest= ' addgroup ', help= ' Add host group ')
Parser.add_argument ('-C ', '--add-host ', dest= ' Addhost ', nargs=3,metavar= (' 192.168.2.1 ', ' test01,test02 ', ' Template01,template02 '), help= ' Add host, multiple host groups or templates using semicolons ')
Parser.add_argument ('-d ', '--disable ', dest= ' Disablehost ', nargs=1,metavar= (' 192.168.2.1 '), help= ' Disable host ')
Parser.add_argument ('-l ', '--allin ', dest= ' Allin ', nargs= '? ', default= ' Allin ', help= ' bulk Import from Excel host ')
Parser.add_argument ('-d ', '--delete ', dest= ' deletehost ', nargs= ' + ', metavar= (' 192.168.2.1 '), help= ' Delete host, multiple hosts with semicolons ')
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 (a Rgs.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名 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].c Ell (row, 3). Value hosttemp = Workbook.sheets () [0].cell (Row, 4). Value Zabbix. Host_create_andy (Hostname,visible,hostip,hostgroup, Hosttemp)

Please revise the above Red label according to the actual situation.

Upload python script zabbix_host.py to Zabbix server

[email protected] temp]# LL
Total 1964
-rwxr-xr-x 1 root root 14644 Dec 23:28 zabbix_host.py

[Email protected] temp]# chown Zabbix:zabbix zabbix_host.py #修改属组属主
[Email protected] temp]# chmod +x zabbix_host.py #添加执行权限

Execute script: Python zabbix_host.py

Each parameter has a detailed description

You might as well play a game.
We use the imported xlsx file in this way: Python zabbix_host.py-l zabbix_host_add.xlsx
The following results show that the add succeeds:

Then go to the web to see it, this is the Zabbix API simple application.

Python uses the Zabbix API to add monitoring

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.