Edits history of script submission #24078 for ' Get AP info (aruba_instant)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Get AP info
     * Run `show version` on an Instant AP through the REST show-command API and return the raw CLI output.
     */
    export async function main(
      auth: RT.ArubaInstant,
      iap_ip_addr: string | undefined
    ) {
      return await showCommand(auth, "show version", iap_ip_addr)
    }
    
    // Instant REST API: POST /rest/login returns a session id (sid) that every
    // monitoring call passes as a query parameter; GET /rest/show-cmd runs a CLI show command.
    async function showCommand(
      auth: RT.ArubaInstant,
      cmd: string,
      iap_ip_addr: string | undefined
    ) {
      const base = auth.base_url.replace(/\/+$/, "")
    
      const login = await fetch(`${base}/rest/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({ user: auth.username, passwd: auth.password }),
      })
      if (!login.ok) {
        throw new Error(`login: ${login.status} ${await login.text()}`)
      }
      const session = (await login.json()) as { Status?: string; sid?: string }
      if (session.Status !== "Success" || !session.sid) {
        throw new Error(`login: ${JSON.stringify(session)}`)
      }
    
      // iap_ip_addr must be the IPv4 address of the AP to query; default to the conductor
      // Built by hand so spaces in cmd are sent as %20, not "+"
      const ip = iap_ip_addr || new URL(base).hostname
      const url =
        `${base}/rest/show-cmd?iap_ip_addr=${encodeURIComponent(ip)}` +
        `&cmd=${encodeURIComponent(cmd)}&sid=${encodeURIComponent(session.sid)}`
    
      try {
        const response = await fetch(url, {
          headers: { Accept: "application/json" },
        })
        if (!response.ok) {
          throw new Error(`${response.status} ${await response.text()}`)
        }
    
        const result = (await response.json()) as { [key: string]: any }
        return { ...result, output: result["Command output"] }
      } finally {
        // Best-effort logout so sessions don't pile up until the inactivity timeout
        // (instantpy: POST /rest/logout with sid); failures are ignored
        await fetch(`${base}/rest/logout?sid=${encodeURIComponent(session.sid)}`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ sid: session.sid }),
        }).catch(() => {})
      }
    }
    

    Submitted by hugo989 7 hours ago