从主机 Inventory 调用特定数据的字符串

String to call specific data from a host Inventory

正在寻找有关如何让此代码指向 Zabbix 中正确清单的一些指导 API。

目前它正在从清单 > 主机 > 最新数据中提取所有数据。

基本上我正在尝试对此进行更改,以请求数据抓取转到库存 > 主机 > > 详细信息,然后抓取以下 'Location latitude' 和 'Location longitude'

我的第一个假设是 def() getInventory 中的应用程序是更改的罪魁祸首,但似乎即使我更改了我的输出也是相同的。

如果您需要任何进一步的信息,请告诉我。

import sys
import datetime
import csv
import re
import requests
import tkinter as tk
from tkinter import filedialog
from pyzabbix import ZabbixAPI,ZabbixAPIException


def initializeapi():
    tries = 4
    while tries >= 0:
        user = "XXX"
        password = "XXX"
        if isinstance(user, str) == True and isinstance(password, str) == True:
            try:
                z.login(user=user,password=password)
                print("Logged into ZabbixAPI version " + z.api_version() + ".")
                return True
            except ZabbixAPIException as e:
                print(e)
                tries -= 1
            except requests.Timeout as f:
                print(f, "\nProgram will now exit.")
                sys.exit(2)
        else:
            print("Username and password must be strings.")
    else:
        print("Too many failed login attempts.")
        return False


def getinventory(listname, hostid='',):
    if isinstance(listname, list):
        if len(hostid) != 0:
            for i in z.item.get(output='extend', hostids=hostid, application='Monitoring'):
                 j = [i['hostid'], i['itemid'], i['name'], i['lastvalue'], i['units'], i['description'], i["location_lon"]]
                 listname.append(j)
        else:
            for i in z.item.get(output='extend', application='Monitoring'):
                 j = [i['hostid'], i['itemid'], i['name'], i['lastvalue'], i['units'], i['description']]
                 listname.append(j)
    else:
        print("Must pass list variable.")
        return False
    return True


def validateserver(serverip):
    if re.search('http://', serverip):
        return True
    elif re.search('https://', serverip):
        return True
    else:
        return False


def gethostdict(dictname):
    if isinstance(dictname, dict):
        for h in z.host.get(output="extend"):
            dictname[h['hostid']] = h['name']
    else:
        print("Must pass dict variable.")
        return False
    return True

def hostchange(listname, dictname):
    for index, item in enumerate(listname):
        if isinstance(item, list):
            hostchange(item, dictname)
        elif item in dictname.keys():
            listname[index] = dictname[item]
    return


def writecsv(writelist):
    with open(getfilepath(), 'w', newline='', encoding="utf-8") as result:
        writer = csv.writer(result, dialect='excel')
        header = ['Host', 'Item ID', 'Name', 'Value', 'Units', 'Description',]
        writer.writerow(header)
        writer.writerows(writelist)


def getfilepath():
    root = tk.Tk()
    return filedialog.asksaveasfilename(initialdir=r'XXX', defaultextension='.csv',
                                             initialfile='Inventory ' + str(datetime.date.today()),
                                             filetypes=(("Comma Separated Values",'*.csv'),("All Files", '*.*')))


if __name__ == '__main__':
    retries = 4
    while retries >= 0:
        serverip = "XXX"
        if validateserver(serverip):
            timeout = 3.5
            try:
                z = ZabbixAPI(str(serverip), timeout=timeout)
            except ZabbixAPIException as e:
                print(e)
            if initializeapi():
                break
        elif retries > 0:
            retries -= 1
        else:
            print("Too many failed attempts.")
            sys.exit(2)
    list1 = []
    dict1 = {}
    getinventory(list1)
    gethostdict(dict1)
    hostchange(list1, dict1)
    writecsv(list1)
    print("Complete.")

参考此文档.. https://www.zabbix.com/documentation/current/en/manual/api/reference/host/object#host-inventory.。 下面的简单 python 脚本对我有用

#using token
import requests
import json
# replace <your zabbix server ip> in url
url = 'http://<your zabbix server ip>/api_jsonrpc.php' 
#replace <your zabbix auth token> in payload
payload = '{"jsonrpc": "2.0", "method": "host.get", "params": {"output": ["hostid","host","name","status"],"selectInventory": ["os_full","tag","location","location_lat","location_lon"]}, "auth": "<your zabbix auth token>", "id": 1 }'
headers = {'content-type': 'application/json-rpc'}
r = requests.post(url, data=payload, headers=headers)
hostslist = r.json()['result']
print(hostlist)

这里是 Python 使用用户名和密码的脚本

from pyzabbix import ZabbixAPI

ZABBIX_SERVER = 'http://<your zabbix server>'
with ZabbixAPI(ZABBIX_SERVER) as zapi:
    zapi.login('<username>', '<password>')
    hosts = zapi.host.get(output=['hostid','itemid','name','lastvalue','units','desciption'], selectInventory=['location','location_lat','location_lon'])
    for host in hosts:
        print(host)