0

Get AP info

by
Published today

Run show version on an Instant AP through its REST API and return the output.

Script aruba_instant Verified

The script

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

3
/**
4
 * Get AP info
5
 * Run `show version` on an Instant AP through the REST show-command API and return the raw CLI output.
6
 */
7
export async function main(
8
  auth: RT.ArubaInstant,
9
  iap_ip_addr: string | undefined
10
) {
11
  return await showCommand(auth, "show version", iap_ip_addr)
12
}
13

14
// Instant REST API: POST /rest/login returns a session id (sid) that every
15
// monitoring call passes as a query parameter; GET /rest/show-cmd runs a CLI show command.
16
async function showCommand(
17
  auth: RT.ArubaInstant,
18
  cmd: string,
19
  iap_ip_addr: string | undefined
20
) {
21
  const base = auth.base_url.replace(/\/+$/, "")
22

23
  const login = await fetch(`${base}/rest/login`, {
24
    method: "POST",
25
    headers: { "Content-Type": "application/json", Accept: "application/json" },
26
    body: JSON.stringify({ user: auth.username, passwd: auth.password }),
27
  })
28
  if (!login.ok) {
29
    throw new Error(`login: ${login.status} ${await login.text()}`)
30
  }
31
  const session = (await login.json()) as { Status?: string; sid?: string }
32
  if (session.Status !== "Success" || !session.sid) {
33
    throw new Error(`login: ${JSON.stringify(session)}`)
34
  }
35

36
  // iap_ip_addr must be the IPv4 address of the AP to query; default to the conductor
37
  // Built by hand so spaces in cmd are sent as %20, not "+"
38
  const ip = iap_ip_addr || new URL(base).hostname
39
  const url =
40
    `${base}/rest/show-cmd?iap_ip_addr=${encodeURIComponent(ip)}` +
41
    `&cmd=${encodeURIComponent(cmd)}&sid=${encodeURIComponent(session.sid)}`
42

43
  try {
44
    const response = await fetch(url, {
45
      headers: { Accept: "application/json" },
46
    })
47
    if (!response.ok) {
48
      throw new Error(`${response.status} ${await response.text()}`)
49
    }
50

51
    const result = (await response.json()) as { [key: string]: any }
52
    return { ...result, output: result["Command output"] }
53
  } finally {
54
    // Best-effort logout so sessions don't pile up until the inactivity timeout
55
    // (instantpy: POST /rest/logout with sid); failures are ignored
56
    await fetch(`${base}/rest/logout?sid=${encodeURIComponent(session.sid)}`, {
57
      method: "POST",
58
      headers: { "Content-Type": "application/json" },
59
      body: JSON.stringify({ sid: session.sid }),
60
    }).catch(() => {})
61
  }
62
}
63