Edits history of script submission #24114 for ' List devices (fortimanager)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * List devices
     * List the managed devices of an ADOM, one page at a time. Pass next_offset back as offset to get the next page (null when this was the last page).
     */
    export async function main(
      auth: RT.Fortimanager,
      adom: string,
      fields: string[] | undefined,
      offset: number | undefined,
      limit: number | undefined
    ) {
      // The ADOM is a segment of the JSON-RPC url: a "/" would address another table.
      if (adom.includes("/")) throw new Error(`Invalid adom: ${adom}`)
      const start = offset ?? 0
      const size = limit || 100
      const params: { [key: string]: any } = {
        url: `/dvmdb/adom/${adom}/device`,
        range: [start, size],
      }
      if (fields?.length) {
        params.fields = fields
      }
    
      const response = await fetch(`${auth.base_url.replace(/\/+$/, "")}/jsonrpc`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          id: 1,
          method: "get",
          params: [params],
          verbose: 1,
        }),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const json = await response.json()
      const result = json.result?.[0]
      if (result?.status?.code !== 0) {
        throw new Error(
          `FortiManager error: ${JSON.stringify(json.result ?? json)}`
        )
      }
    
      const devices: any[] = result.data ?? []
      return {
        devices,
        offset: start,
        limit: size,
        next_offset: devices.length === size ? start + size : null,
      }
    }
    

    Submitted by hugo989 6 hours ago