Edits history of script submission #23992 for ' List hosts (zabbix)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * List hosts
     * List hosts (host.get) filtered by exact technical host names, a case-insensitive substring of the visible name, or host group IDs; returns hostid, host, name, status (0 enabled, 1 disabled) and hostgroups. The Zabbix API has no offset: has_more tells you the limit cut the result, so narrow the filters or raise the limit.
     */
    export async function main(
      auth: RT.Zabbix,
      host_names: string[] | undefined,
      name_search: string | undefined,
      group_ids: string[] | undefined,
      limit: number | undefined
    ) {
      const max = Math.max(1, limit || 100)
      const params: { [key: string]: any } = {
        output: ["hostid", "host", "name", "status"],
        selectHostGroups: ["groupid", "name"],
        sortfield: "hostid",
        limit: max + 1,
      }
      if (host_names?.length) {
        params.filter = { host: host_names }
      }
      if (name_search) {
        params.search = { name: name_search }
      }
      if (group_ids?.length) {
        params.groupids = group_ids
      }
    
      const hosts = await call(auth, "host.get", params)
      return { hosts: hosts.slice(0, max), has_more: hosts.length > max }
    }
    
    async function call(auth: RT.Zabbix, method: string, params: any) {
      const response = await fetch(
        `${auth.base_url.replace(/\/+$/, "").replace(/\/api_jsonrpc\.php$/, "")}/api_jsonrpc.php`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json-rpc",
            Accept: "application/json",
          },
          body: JSON.stringify({ jsonrpc: "2.0", method, params, id: 1 }),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const text = await response.text()
      let data: any
      try {
        data = JSON.parse(text)
      } catch {
        throw new Error(
          `Not a JSON-RPC response (check base_url): ${text.slice(0, 300)}`
        )
      }
      if (data.error) {
        throw new Error(
          `${data.error.code} ${data.error.message} ${data.error.data ?? ""}`
        )
      }
      return data.result
    }
    

    Submitted by hugo989 3 hours ago