0

List devices

by
Published today

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).

Script fortimanager Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 6 hours ago
1
//native
2

3
/**
4
 * List devices
5
 * 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).
6
 */
7
export async function main(
8
  auth: RT.Fortimanager,
9
  adom: string,
10
  fields: string[] | undefined,
11
  offset: number | undefined,
12
  limit: number | undefined
13
) {
14
  // The ADOM is a segment of the JSON-RPC url: a "/" would address another table.
15
  if (adom.includes("/")) throw new Error(`Invalid adom: ${adom}`)
16
  const start = offset ?? 0
17
  const size = limit || 100
18
  const params: { [key: string]: any } = {
19
    url: `/dvmdb/adom/${adom}/device`,
20
    range: [start, size],
21
  }
22
  if (fields?.length) {
23
    params.fields = fields
24
  }
25

26
  const response = await fetch(`${auth.base_url.replace(/\/+$/, "")}/jsonrpc`, {
27
    method: "POST",
28
    headers: {
29
      Authorization: `Bearer ${auth.token}`,
30
      "Content-Type": "application/json",
31
      Accept: "application/json",
32
    },
33
    body: JSON.stringify({
34
      id: 1,
35
      method: "get",
36
      params: [params],
37
      verbose: 1,
38
    }),
39
  })
40

41
  if (!response.ok) {
42
    throw new Error(`${response.status} ${await response.text()}`)
43
  }
44

45
  const json = await response.json()
46
  const result = json.result?.[0]
47
  if (result?.status?.code !== 0) {
48
    throw new Error(
49
      `FortiManager error: ${JSON.stringify(json.result ?? json)}`
50
    )
51
  }
52

53
  const devices: any[] = result.data ?? []
54
  return {
55
    devices,
56
    offset: start,
57
    limit: size,
58
    next_offset: devices.length === size ? start + size : null,
59
  }
60
}
61