0

Get running config

by
Published today

Return the running configuration of a Cisco Nexus switch, whole or for one section.

Script cisco_nxos Verified

The script

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

3
/**
4
 * Get running config
5
 * Return the switch's running configuration as text: the whole configuration, or one section when `section` is set (anything accepted after `show running-config`, e.g. "interface Ethernet1/1", "bgp", "vlan").
6
 */
7
export async function main(auth: RT.CiscoNxos, section: string | undefined) {
8
  // NX-API splits input on ';', which would run extra commands.
9
  if (section?.includes(";")) {
10
    throw new Error("section must not contain ';'")
11
  }
12
  const command = section?.trim()
13
    ? `show running-config ${section.trim()}`
14
    : "show running-config"
15

16
  const [output] = await nxapi(auth, "cli_show_ascii", [command])
17

18
  return { command, config: output?.body ?? "" }
19
}
20

21
type NxapiOutput = {
22
  input?: string
23
  body?: any
24
  code: string
25
  msg?: string
26
  clierror?: string
27
}
28

29
async function nxapi(
30
  auth: RT.CiscoNxos,
31
  type: "cli_show" | "cli_show_ascii" | "cli_conf",
32
  commands: string[]
33
): Promise<NxapiOutput[]> {
34
  const response = await fetch(new URL("/ins", auth.base_url), {
35
    method: "POST",
36
    headers: {
37
      Authorization: `Basic ${btoa(`${auth.username}:${auth.password}`)}`,
38
      "Content-Type": "application/json",
39
      Accept: "application/json",
40
    },
41
    // Keep "type" before "input": some NX-OS releases misparse the payload otherwise
42
    body: JSON.stringify({
43
      ins_api: {
44
        version: "1.0",
45
        type,
46
        chunk: "0",
47
        sid: null,
48
        input: commands.join(" ;"),
49
        output_format: "json",
50
      },
51
    }),
52
  })
53

54
  if (!response.ok) {
55
    throw new Error(`${response.status} ${await response.text()}`)
56
  }
57
  const text = await response.text()
58
  if (text.trimStart().startsWith("<")) {
59
    // NX-API falls back to XML when the output exceeds 1 MB
60
    throw new Error(
61
      `NX-API returned XML instead of JSON (outputs over 1 MB come back as XML): ${text.slice(0, 500)}`
62
    )
63
  }
64

65
  const data = JSON.parse(text)
66
  const raw = data?.ins_api?.outputs?.output
67
  const outputs: NxapiOutput[] =
68
    raw == null ? [] : Array.isArray(raw) ? raw : [raw]
69
  for (const o of outputs) {
70
    if (String(o.code) !== "200") {
71
      throw new Error(
72
        `${o.code} ${o.input ?? ""}: ${o.msg ?? ""} ${o.clierror ?? ""}`.trim()
73
      )
74
    }
75
  }
76
  return outputs
77
}
78