Search code examples
pythonzabbixzabbix-api

Pulling Zabbix Data into csv file


Can't seem to find the correct syntax to get the request I need.

At this point I am able to connect to my Zabbix server via an API. I'm able to see all the data that I need which is confirmed by a simple print() function.

However, I am blanking at the way to get the data from the variable into a csv file.

from pyzabbix import ZabbiXAPI

        zapi = ZabbixAPI("example")
        zapi.login("example", "example")
    
    for hostInventory in zapi.host.get():
        print(hostInventory)

This then spits out about 500 lines of this approx - obviously redacted sensitive information:

{'hostid': 'xxx', 'proxy_hostid': 'xxx', 'host': 'xxx', 'status': 'x', 'lastaccess': 'x', 'ipmi_authtype': 'x', 'ipmi_privilege': 'x', 'ipmi_username': 'x', 'ipmi_password': 'x', 'maintenanceid': 'x', 
'maintenance_status': 'x', 'maintenance_type': 'x', 'maintenance_from': 'x', 'name': 'x', 'flags': 'x', 'templateid': 'x', 'description': 'x', 'tls_connect': 'x', 'tls_accept': 'x', 'tls_issuer': 'x', 'tls_subject': 'x', 'proxy_address': 'x', 'auto_compress': 'x', 'custom_interfaces': 'x', 'uuid': 'x', 'inventory_mode': 'x'}

If I need to provide any further information please let me know. First time poster.


Solution

  • You have to learn standard module csv or popular pandas
    (and this problem has nothing to do directly with Zabbix).

    With pandas it should be much simpler.

    import pandas as pd
    
    data = list( zapi.host.get() )
    df = pd.DataFrame(data)
    
    df.to_csv('output.csv')
    

    Eventually you may have to use own code to create dictionaries

    data = []
    
    for hostInventory in zapi.host.get():
        item = {"hostid": hostInventory.hostid, ...}
        data.append(item)