Ad Widget

Collapse

Script to add multiple hosts via command line

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Stephen J Capita
    Junior Member
    • Mar 2022
    • 13

    #1

    Script to add multiple hosts via command line

    Up until today we have been using Zabbix version 6.0lts, we decided to upgrade to version 7.0lts Currently running Alma Linux 8, zabbix 7.0.9lts and mysql. We had a script that we use to add multiple servers at once to zabbix via the command line. The script is a python 3 script that uses the ZabbixAPI. You add the servers into a CSV file, then the script checks if the servers are already added, if not it runs through and adds them.

    Here is a copy of the script:

    Code:
    #!/usr/bin/env python3
    # import hosts from txt file to Zabbix via API
    # and assign template and host group to them
    
    # python3 required
    # dnf install python3-pip
    # pip3 install zabbix_api
    # script is tested and works with module 'zabbix_api'
    # which is not the same as 'pyzabbix' !
    import csv
    
    from zabbix_api import ZabbixAPI
    
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.Insecu reRequestWarning)
    
    import sys
    sys.path.insert(0,'/var/lib/zabbix')
    
    # pip install config
    import config
    ZABBIX_SERVER = config.url
    zapi = ZabbixAPI(ZABBIX_SERVER)
    zapi.session.verify=False
    zapi.login(config.username, config.password)
    
    file = open("servers.csv",'rt')
    reader = csv.DictReader( file )
    
    # take the file and read line by line
    for line in reader:
    # check if this host exists in zabbix
    if not zapi.host.get({"filter":{"host" :line['name']}}):
    print (line['name'],"not yet registred")
    if zapi.proxy.get({"output": "proxyid","selectInterface": "extend","filter":{"host":line['proxy']}}):
    proxy_id=zapi.proxy.get({"output": "proxyid","selectInterface": "extend","filter":{"host":line['proxy']}})[0]['proxyid']
    print (line['proxy'])
    if int(proxy_id)>0:
    templates=line['template'].split(";")
    groups=line['group'].split(";")
    group_id = zapi.hostgroup.get({"filter" : {"name" : groups}, "output": "groupid"})
    template_id = zapi.template.get({"filter" : {"name" : templates}, "output": "templateid"})
    # crete a host an put hostid instantly in the 'hostid' variable
    hostid = zapi.host.create ({
    "host":line['name'],"interfaces":[{"type":1,"dns": line['dns'],"main":1,"ip": line['address'],"port": 10050,"useip": 1,"details":{"version":"2","bulk":"1","community ": "{$SNMP_COMMUNITY}"}}],
    "groups": group_id ,
    "proxy_hostid":proxy_id,
    "templates": template_id })['hostids']
    
    # if there are no proxy
    else:
    print ("proxy does not exist. creating with none")
    templates=line['template'].split(";")
    groups=line['group'].split(";")
    group_id = zapi.hostgroup.get({"filter" : {"name" : groups}, "output": "groupid"})
    template_id = zapi.template.get({"filter" : {"name" : templates}, "output": "templateid"})
    
    # create a host an put hostid instantly in the 'hostid' variable
    hostid = zapi.host.create ({
    "host":line['name'],"interfaces":[{"type":1,"dns": line['dns'],"main":1,"ip": line['address'],"port": 10050,"useip": 1,"details":{"version":"2","bulk":"1","community ": "{$SNMP_COMMUNITY}"}}],
    "groups": group_id,
    "templates": template_id })['hostids']
    
    else:
    print (line['name'], " already exists")
    file.close()
    This worked fine on version 6, but it seems to have changed on version 7.

    When I try to run the script I get the following error:

    Code:
    Traceback (most recent call last):
    File "./vm.py", line 25, in <module>
    zapi.login(config.username, config.password)
    File "/usr/local/lib/python3.6/site-packages/zabbix_api.py", line 207, in login
    result = self.do_request(obj)
    File "/usr/local/lib/python3.6/site-packages/zabbix_api.py", line 299, in do_request
    raise ZabbixAPIException(msg, jobj['error']['code'])
    zabbix_api.ZabbixAPIException: ('Error -32602: Invalid params., Invalid parameter "/": unexpected parameter "user". while sending {"jsonrpc": "2.0", "method": "user.login", "params": {"user": "example", "password": "example"}, "id": 0}', -32602)

    I logged a call with zabbix support, they said that between zabbix 6 and 7 the login authentication has changed. I am having trouble getting it to autheticate.
  • PavelZ
    Senior Member
    • Dec 2024
    • 162

    #2
    One of the easiest ways to transfer hosts is to export and import to yaml.

    Don't you want to try?

    Comment

    • Stephen J Capita
      Junior Member
      • Mar 2022
      • 13

      #3
      These will be new hosts that I am creating in zabbix. There can be up to 10 or more at a time, having the script to do it for me was very convenient. I would be keen to try and change the script so it works with the new auth methods

      Comment

      • Stephen J Capita
        Junior Member
        • Mar 2022
        • 13

        #4
        I was able to change the zabbbix_apy.py file and change it so it now logs in. The script can now read if the server is created. If not it will attempt to create it, but it is having a issue with proxy and group. These names must have changed from version 6.0 to version 7.0 Click image for larger version

Name:	Error.png
Views:	547
Size:	68.4 KB
ID:	499010

        Comment

        • cyber
          Senior Member
          Zabbix Certified SpecialistZabbix Certified Professional
          • Dec 2006
          • 4807

          #5
          I would suggest to use native python library.. https://github.com/zabbix/python-zab...main/README.md

          Comment

          • Brambo
            Senior Member
            • Jul 2023
            • 245

            #6
            I don't use python but it seems your problem is login and get a working session.
            Why not use the API token option for this?
            Your POST header should look like (example from powershell)
            Code:
            $headers.add('Content-Type' , 'application/json')
            $headers.add('Authorization' , "Bearer $apikey")
            And your post body is the json you want to add (the host info) and send all towards <zserver>/api_jsonrpc.php.
            No need to login and create a session token etc etc. The API token can easily be enable / disabled and no need to expose the user credentials.

            Comment

            • cyber
              Senior Member
              Zabbix Certified SpecialistZabbix Certified Professional
              • Dec 2006
              • 4807

              #7
              With native python library you can use tokens also.. no need for any headers etc..

              Comment

              • Stephen J Capita
                Junior Member
                • Mar 2022
                • 13

                #8
                I decided to give up on the python script. I ended up going with @PavelZ idea of importing XML files. I setup a spreadsheet that all I need to do is drop in the server name and IP. It then autogenerates all the xml fields like groups, template name etc. As a first draft it works really well.

                I then simply copy the xml lines and drop them into an XML file and use the upload functionality as well. The great thing as well is we pay for dedicated zabbix support. This method is supported by zabbix, rather than the python which wasn't. It was also a bit of a pain each time to have to use filezilla to upload the file to the zabbix box, then run different scripts based on the type of server. This new way is a one-shot deal and adds all the servers in at the same time!

                I might even go as afar as writing a vb script with two input boxes, one for the server name, one for the IP. I could then get VB to fully generate an xml file for me, but that could be overkill!

                Comment

                • vsergione
                  Junior Member
                  • Oct 2023
                  • 28

                  #9
                  You could take a look at https://zbxwizz.app. What you have here is a 10 min job with this tool.

                  Comment

                  • PavelZ
                    Senior Member
                    • Dec 2024
                    • 162

                    #10
                    I will remind you that there is also an ansible role, so you can combine host configuration and host registration in zabbix. And also a terraform provider (I think there are two)

                    And by the way, I meant YAML - this format looks less scary

                    Comment

                    • Stephen J Capita
                      Junior Member
                      • Mar 2022
                      • 13

                      #11
                      Originally posted by PavelZ
                      I will remind you that there is also an ansible role, so you can combine host configuration and host registration in zabbix. And also a terraform provider (I think there are two)

                      And by the way, I meant YAML - this format looks less scary
                      I ended up with xml. Zabbix provided me with a youtube document on how to create xml files, with a load of different types of hosts. I import an ESX host which I monitor via SNMP, 4 windows vms monitored by zabbix agent and a ups monitored by snmp. Using the spreadsheet I just need to fill in the server names and IP's, then my formula I setup generates the xml line of code that I need for each server. I then copy the lines into an xml file and upload job done. Now I have the spreadsheet setup it is even easier than the python script I used.

                      The video zabbix suggested is this one and it works perfectly for what I need!

                      Comment

                      • troffasky
                        Senior Member
                        • Jul 2008
                        • 567

                        #12
                        I actually got ChatGPT to write me a python script to do this, which was....OK...ish.
                        I then found this which was more effective: https://github.com/intellitrend/zabb...-import-module
                        TBH using the native format would be "Best" as you often miss little things here and there when creating the CSV import file, eg, some host has a non-standard SNMP port or unexpected community, etc.

                        Comment

                        Working...