Edits history of script submission #24010 for ' Get device info (cisco_iosxe)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Get device info
     * Get the hostname, software version, platform (chassis part number) and serial number of a Cisco IOS XE device over RESTCONF.
     */
    export async function main(auth: RT.CiscoIosxe) {
      const headers = {
        Authorization: `Basic ${btoa(`${auth.username}:${auth.password}`)}`,
        Accept: "application/yang-data+json",
      }
    
      const [hostnameResponse, hardwareResponse] = await Promise.all([
        fetch(
          new URL(
            `${auth.base_url.replace(/\/+$/, "")}/restconf/data/Cisco-IOS-XE-native:native/hostname`
          ),
          { headers }
        ),
        fetch(
          new URL(
            `${auth.base_url.replace(/\/+$/, "")}/restconf/data/Cisco-IOS-XE-device-hardware-oper:device-hardware-data/device-hardware`
          ),
          { headers }
        ),
      ])
    
      if (!hostnameResponse.ok) {
        throw new Error(
          `${hostnameResponse.status} ${await hostnameResponse.text()}`
        )
      }
      if (!hardwareResponse.ok) {
        throw new Error(
          `${hardwareResponse.status} ${await hardwareResponse.text()}`
        )
      }
    
      const hostname = (await hostnameResponse.json())[
        "Cisco-IOS-XE-native:hostname"
      ]
      // RFC 8040 wraps the response in the target node; Cisco DevNet's generated
      // examples show the module root wrapper instead, so accept both.
      const hardwareBody = await hardwareResponse.json()
      const hardware =
        hardwareBody["Cisco-IOS-XE-device-hardware-oper:device-hardware"] ??
        hardwareBody["Cisco-IOS-XE-device-hardware-oper:device-hardware-data"]?.[
          "device-hardware"
        ]
      const system = hardware?.["device-system-data"] ?? {}
      // A stack or a modular chassis reports one hw-type-chassis entry per member.
      const chassis = (hardware?.["device-inventory"] ?? [])
        .filter((item: any) => item["hw-type"] === "hw-type-chassis")
        .sort(
          (a: any, b: any) => Number(a["hw-dev-index"]) - Number(b["hw-dev-index"])
        )
    
      return {
        hostname,
        software_version: system["software-version"],
        platform: chassis[0]?.["part-number"],
        serial_number: chassis[0]?.["serial-number"],
        chassis,
        system_data: system,
      }
    }
    

    Submitted by hugo989 2 hours ago