pathlib, writing files & running-config backups
Back up every configuration
Lesson 13 of 20 · 12 min · Module 4: Backups, drift and compliance
Before any change, take a backup. A folder of configuration files is also where drift detection and compliance checks start.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Create a folder that may already exist
- Write and read text files with pathlib
- Use the right command for each vendor
The idea
pathlib.Path handles folders and files: Path("backups").mkdir(exist_ok=True) creates a folder unless it exists already, and (folder / "sw1.cfg").write_text(text) writes a file. Cisco calls the active configuration show running-config; Huawei calls it display current-configuration. Name each file after the device, so the next script can find it.
from pathlib import Path
folder = Path("backups")
folder.mkdir(exist_ok=True)
(folder / "demo.cfg").write_text("hostname demo\n")
print(sorted(p.name for p in folder.iterdir()))
01A folder for the backups
exist_ok=True makes mkdir succeed when the folder is already there, so the script can run every night.
from pathlib import Path
folder = Path("backups")
folder.mkdir(exist_ok=True)
folder.mkdir(exist_ok=True)
print(folder.is_dir())True02Write, then read back
write_text replaces the whole file. read_text returns it as one string.
(folder / "note.cfg").write_text("hostname demo\n!\nend\n")
print((folder / "note.cfg").read_text().splitlines())['hostname demo', '!', 'end']03Huawei calls it current-configuration
The first lines tell you when the configuration last changed and when it was saved.
import os
from netmiko import ConnectHandler
USERNAME = os.environ["NET_USERNAME"]
PASSWORD = os.environ["NET_PASSWORD"]
with ConnectHandler(device_type="huawei", host="10.0.1.12",
username=USERNAME, password=PASSWORD) as conn:
text = conn.send_command("display current-configuration")
print("\n".join(text.splitlines()[:6]))!Software Version V200R022C00SPC500
!Last configuration was updated at 2026-10-16 02:00:00+00:00 by netadmin
!Last configuration was saved at 2026-10-16 02:00:00+00:00 by netadmin
#
sysname sw5
#Your turn
devices.csv to backups/<name>.cfg, using the right command for each platform. Build saved, the list of device names you backed up, in file order. Skip devices that do not answer.What the checks look for
- saved lists the reachable devices
- There is one backup file per reachable device
- Cisco backups hold the running configuration
- Huawei backups hold the current configuration
Take this with you
Back up before you change: one file per device, named after the device.
Go a little further
Add today's date to each file name, for example backups/sw1-2026-10-19.cfg, with datetime.date.today().isoformat().