Skip to content

Lab 13 - Challenge - Saving and Backing Up Configs

Using only what has been covered in previous labs, use Netmiko to:

  • Save the running configuration with write memory.
  • Retrieve the running configuration to your jump host.
  • Save it into a file placed in /home/ntc/labs/python/configs.
  • Each file should be named after its router e.g. csr1.cfg.
  • Add a print statement before each of the four actions are executed in your script:
  • Connecting to the device
  • Saving the configuration
  • Backing up configuration
  • Writing configuration to file
  • Perform this operation first for csr1, then for csr2.

Save this script in the /home/ntc/labs/python directory and call it backup.py. You will also have to create a new folder: mkdir -p /home/ntc/labs/python/configs.

After you execute the backup script, open the csr1.cfg and csr2.cfg files in your editor of choice and ensure they have the correct contents!

Reveal Solution
#! /usr/bin/env python

from netmiko import ConnectHandler

print("Connecting to device | CSR1")

csr1 = ConnectHandler(
    host="csr1", username="ntc", password="ntc123", device_type="cisco_ios"
)

print("Saving configuration | CSR1")

csr1.send_command("wr mem")

print("Backing up configuration | CSR1")

csr1.send_command("term len 0")
csr1_config = csr1.send_command("show run")

print("Writing config to file | CSR1\n")

with open("/home/ntc/labs/python/configs/csr1.cfg", "w") as config_file:
    config_file.write(csr1_config)

print("Connecting to device | CSR2")

csr2 = ConnectHandler(
    host="csr2", username="ntc", password="ntc123", device_type="cisco_ios"
)

print("Saving configuration | CSR2")

csr2.send_command("wr mem")

print("Backing up configuration | CSR2")

csr2.send_command("term len 0")
csr2_config = csr2.send_command("show run")

print("Writing config to file | CSR2\n")

with open("/home/ntc/labs/python/configs/csr2.cfg", "w") as config_file:
    config_file.write(csr2_config)
ntc@ntc-training:python$ python backup.py
Connecting to device | CSR1
Saving configuration | CSR1
Backing up configuration | CSR1
Writing config to file | CSR1

Connecting to device | CSR2
Saving configuration | CSR2
Backing up configuration | CSR2
Writing config to file | CSR2

ntc@ntc-training:python$ grep hostname configs/*
configs/csr1.cfg:hostname csr1
configs/csr2.cfg:hostname csr2