Search code examples
powershellzabbix

Powershell get Zabbix Hosts via API


Im trying to use powershell to get host data from the Zabbix API.

I want to get the following columns back for host groups 15, 24, 26:

  • hostid
  • host
  • status
  • interfaceid
  • ip
  • dns
  • useip

If I use Postman to submit the query, I would submit the following which works:

{
    "jsonrpc": "2.0",
    "method": "host.get",
    "params": {
        "output": [
            "hostid",
            "host",
            "status"
        ],
        "groupids": [15, 24, 26],
        "selectInterfaces": [
            "interfaceid",
            "ip",
            "dns",
            "useip"
        ]
    },
    "id": 2,
    "auth": "xxxxxxxxxxxxx"
}

So far I have the following powershell which returns a lot of information

$params.body = @{
    "jsonrpc"= "2.0"
    "method"= "host.get"
    "params"= @{
        output = "extend"
        selectHosts = "extend"
    }
    auth= "xxxxxxxxxxxxx"
    id= 2
} | ConvertTo-Json

$result = Invoke-WebRequest @params

Write-Host $result

I'm having trouble understanding how to request only the information I want, I've not done a powershell script like this before so would appreciate any guidance.


Solution

  • You need to build your $params.body with the same fields and options you used in Postman:

    $params.body = @{
        "jsonrpc"= "2.0"
        "method"= "host.get"
        "params"= @{
            output = @( "host", "hostid", "status" )
            selectInterfaces = @( "interfaceid", "ip", "dns", "useip" )
            groupids = @( "15", "24", "26")
        }
        auth = xxxxxxxxxxxxx
        id = 2
    } | ConvertTo-Json
    

    You should get something like:

    hostid host        status interfaces                                                                                          
    ------ ----        ------ ----------                                                                                          
    10017  somehost    0      {@{interfaceid=30251; ip=192.168.10.15; dns=; useip=1}}                                               
    10051  anotherone  0      {@{interfaceid=12353; ip=10.10.10.20; dns=tanotherone.mydomain.com; useip=1}}                       
    10054  whatisthis  0      {@{interfaceid=43262; ip=172.16.1.20; dns=; useip=1}}