Get the instance code of IP and host name for all hosts on zabbix

  • 2021-07-06 12:07:37
  • OfStack

zabbix

zabbix ([` z & aelig; biks]) is an enterprise-class open source solution that provides distributed system monitoring and network monitoring capabilities based on the WEB interface.

zabbix can monitor various network parameters to ensure the safe operation of the server system; And provides a flexible notification mechanism to allow system administrators to quickly locate/resolve various existing problems.

zabbix consists of two parts, zabbix server and optional component zabbix agent.

zabbix server can provide remote server/network status monitoring, data collection and other functions through SNMP, zabbix agent, ping, port monitoring and other methods. It can run on Linux, Solaris, HP-UX, AIX, Free BSD, Open BSD, OS X and other platforms.

The following is a code to get the IP and host name of all hosts on zabbix. The code is as follows:


#coding:utf-8
# Get zabbix Of all hosts on the IP And hostname 
import requests
import json
import csv
import time
def get_token():
  data = {
    "jsonrpc": "2.0",
    "method": "user.login",
    "params": {
      "user": username,
      "password": password
    },
    "id": 0
  }
  r = requests.get(zaurl, headers=header, data=json.dumps(data))
  auth = json.loads(r.text)
  return auth["result"]
def getHosts(token):
  data = {
    "jsonrpc": "2.0",
    "method": "host.get",
    "params": {
      "output": [
        "hostid",
        "host"
      ],
      "selectInterfaces": [
        "interfaceid",
        "ip"
      ]
    },
    "id": 2,
    "auth": token,
  }
  request = requests.post(zaurl, headers=header, data=json.dumps(data))
  dict = json.loads(request.content)
#  print (dict['result'])
  return dict['result']
if __name__ == "__main__":
  zaurl="http://xx.xx.xx.xx/zabbix/api_jsonrpc.php"
  header = {"Content-Type": "application/json"}
  username = "xx"
  password = "xx"
  token = get_token()
  hostlist = getHosts(token)
  datafile = "zabbix.txt"
  fdata = open(datafile,'w')
  for i in hostlist:
    hostid = i['hostid']
    hostip = i['host']
    fdata.write(hostip + ' ' + hostid + '\n')
  fdata.close()

Summarize


Related articles: