Advanced
Searching inSummaries
How to search
  • Words find lesson titles, text and code. Filter by type (guides, courses, programs, books) or stay in this book.
  • book:rhcsa and ch:8 narrow the search; #code finds a word only in commands of the lessons.
  • "two words" finds the exact phrase.
  • Plain words find names, texts and examples.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search
Try:

Course 12Name in the course: Network Automation with Python

Network Automation with Python

Course 12 of 13 in the Alta3 Academy library. Alta3 Academy self-paced course.

Note

My result — Lessons read: all 33/33; Course progress: 100%.

  • 13 Lessons
  • 8 Commands
  • 2 Labs

$ run as a normal user# run as root (or with sudo)

12.1

What the course covers

How APIs and HTTP work for network devices.

  • How to call network APIs with the requests library.
  • How to read packet captures with Python (dpkt) and termshark.
  • How to run ICMP checks and search text with regular expressions.
  • How to use SSH from Python with Paramiko, Netmiko, and NAPALM.
  • How to store data in sqlite3 and take input from the command line and environment.
  • How to test code with pytest and speed up HTTP work with threads and asyncio.
  • How to work with network interfaces and Telnet.

12.2

Welcome to Alta3 Research Labs!

The lab host has a student user. ~ is the home folder. A $ prompt means a normal user.

  • The browser pane shows a web page for your app. tmux gives you extra panes.
  • VIRGIL is the AI lab coach. It can explain a step or a command.

12.3

Before You Begin This Course

The course expects Python basics: functions, lists, dictionaries, loops, files, modules, errors, and classes.

  • If those topics are new, take Introduction to Python first.

12.4

Getting Started

Vim: press i to insert, Esc to stop, :wq to save, and :q! to quit without saving.

  • tmux: Ctrl + b then % or " splits the screen. Ctrl + b then an arrow key moves between panes.
  • Panes let you edit a script in one place and run it in another.

12.5

Software Control Management

GitHub or GitLab both work. You make an account, a repo, and a personal access token.

Commands in this lesson

12.6

APIs, Network Diagnostics and Analysis

A network device API lets you read and change a device over HTTP, not only over the CLI.

  • requests.get(url) reads data. requests.post(url, json=data) sends data. resp.status_code checks the result. resp.json() gives Python data.
  • A mock device API runs in Docker: docker run -d --name cisco-router -p 5000:5000 ghcr.io/csfeeser/mock-network-api:latest.
  • curl http://localhost:5000/devices shows the device list. A POST with JSON adds a device.
  • dpkt reads *.pcap files. A with open(..., "rb") block keeps the file open while you loop over packets.
  • dpkt.ethernet.Ethernet(buf) unpacks a frame. The loop gives you a timestamp and the raw bytes for each packet.
  • Newer captures are *.pcapng. Convert them with editcap -F libpcap -T ether trace.pcapng trace.pcap. editcap comes with tshark.
  • termshark -i lo gives a Wireshark-like view in the terminal. Press | to change the layout. Ctrl + c stops a capture.
  • os.system("ping -c 1 " + host) returns 0 when the host answers. A loop can check a list of IPs and names.
  • The re module finds patterns. Groups in (...) pull out the parts you want, such as a phone number, an IPv6 address, or a port.
  • Test a pattern on regex101.com before you put it in a script.

12.7

Remote Network Configuration

Paramiko makes SSH connections in Python. paramiko.SSHClient() makes the client. connect() opens the session. exec_command() runs a command.

  • Paramiko can use a password or an RSA key pair. Never hard-code a secret in your code.
  • getpass.getpass() asks for a password without showing it on the screen.
  • Paramiko SFTP moves files over SSH. open_sftp() starts it. put() uploads. get() downloads. close() ends it.
  • The Cisco NX-OS lab uses a free always-on sandbox. It has SSH on port 22 and a REST API on ports 80 and 443.
  • Over that API you can send a command such as show ver and read the reply. The lab shows the request and the 200 response.
  • Netmiko is a toolkit for network devices. ConnectHandler(device_type=..., ip=..., username=..., password=...) logs in.
  • send_command("show ip int brief") runs one command and returns the text.
  • The Netmiko lab reads hosts from a CSV file. csv.DictReader turns each row into a dict. socket.getaddrinfo() resolves a hostname to an IP.
  • sqlite3 is a small file database. connect(), execute(), commit(), and close() are the main calls.
  • NAPALM gives one API for many vendors. get_network_driver("eos") picks the driver. device.open() connects.
  • device.get_config() returns startup, running, and candidate configs. Running is active now. Startup loads at boot. Candidate is in memory but not active.
  • NAPALM can test a device against a YAML file. device.compliance_report("sw1_validate.yml") returns complies: True or False.
  • A wrong expected value makes the test fail. The report shows the actual value and the expected value, so you can fix the file.
  • The labs use NAPALM 4.1.0 with the Arista eAPI. Start eAPI on the switch with management api http-commands, then no shutdown.

12.8

Additional Labs and Tools

argparse reads command-line arguments. parser.add_argument() defines one. parser.parse_args() reads them. Old scripts used sys.argv.

  • os.getenv("MYPORT", default="8888") reads an environment variable. Containers often use env vars for ports and paths.
  • netifaces lists network interfaces. netifaces.interfaces() returns their names. Install it with python3 -m pip install netifaces.
  • telnetlib makes a Telnet client. Telnet(HOST, PORT, timeout=1) connects. write() sends text. read_all() reads the reply.
  • pytest runs tests. A test function starts with test_. assert checks a result. pytest simpsons_test.py runs one file.
  • Threads start many HTTP requests without waiting for each one. ThreadPoolExecutor(max_workers=5) runs a small pool. as_completed() gives results as they finish.
  • Keep the pool small. A large pool can overload the API you call.
  • asyncio does the same work with one thread. async def makes a coroutine. await pauses it while it waits. aiohttp sends the requests.
  • Use threads or asyncio for I/O-bound work. For CPU-bound work, use multiprocessing instead.
  • python3 -m pip install pytest aiohttp paramiko netmiko installs the main third-party tools.

12.9

Key commands and tools

  • python3 -m pip install requests dpkt paramiko netmiko pytest aiohttp netifaces
  • python3 -m pip install --user "napalm==4.1.0"
  • resp = requests.get("http://localhost:5000/devices") then resp.json()
  • requests.post(url, json={"name": "Switch1", "ip": "192.168.1.1"})
  • docker run -d --name cisco-router -p 5000:5000 ghcr.io/csfeeser/mock-network-api:latest
  • curl -X POST -H "Content-Type: application/json" -d '{"name": "Switch1"}' http://localhost:5000/devices
  • editcap -F libpcap -T ether trace.pcapng trace.pcap
  • sudo apt install tshark and sudo apt install termshark -y, then sudo termshark -i lo
  • pcap = dpkt.pcap.Reader(f) then for ts, buf in pcap:
  • os.system("ping -c 1 " + host) in a loop over a device list
  • re.search(r'sip:\+(\d+)@\[(.*)\]:?(\d+)?', contact) pulls groups out of a SIP header
  • ssh = paramiko.SSHClient() then mykey = paramiko.RSAKey.from_private_key_file(keypath)
  • ssh.connect(hostname=host, username=user, pkey=mykey)
  • stdin, stdout, stderr = ssh.exec_command("show version")
  • sftp = ssh.open_sftp() then sftp.put("local.txt", "/tmp/remote.txt")
  • ConnectHandler(device_type="arista_eos", ip=ip, username=user, password=pw)
  • device = driver("sw-1", "admin", password, optional_args={"transport": "http"})
  • device.compliance_report("/home/student/mycode/sw1_validate.yml")
  • conn = sqlite3.connect("test.db") and conn.execute("CREATE TABLE ...")
  • parser = argparse.ArgumentParser() then parser.add_argument("--ip") and parser.parse_args()
  • os.getenv("MYPORT", default="8888")
  • pytest simpsons_test.py
  • netifaces.interfaces() lists the interface names on the host
  • telnetlib.Telnet("www.python.org", 80, timeout=1) opens a Telnet client
  • asyncio.run(main()) with async with aiohttp.ClientSession() as session:

12.10

Key terms

The words of this course in one table. Learn them before the quiz or exam.

TermMeaning
APIA service that lets a program read or change data.
argparseThe standard module for reading command-line arguments.
asyncioA single-thread way to run many waiting tasks.
Candidate configA config in memory that is not active yet.
CoroutineA function that can pause at await and resume.
eAPIArista's HTTP API for switches.
Environment variableA value from outside the program, read with os.getenv().
ICMPThe protocol behind ping.
InterfaceA network port on a device, such as eth0.
NAPALMOne Python API for many network vendors.
NetmikoA Python toolkit for SSH access to network devices.
NX-OSCisco's operating system for Nexus switches.
ParamikoA Python library for SSH and SFTP.
pcapA file that holds captured network packets.
pcapngA newer packet capture format. Convert it before dpkt reads it.
pytestA tool that runs Python test functions.
RegexA pattern language for finding text.
Running configThe configuration that is active on a device now.
SFTPFile transfer over an SSH connection.
SQLiteA small database that lives in one file.
SSHA secure way to log in to a remote machine.
Startup configThe configuration a device loads when it boots.
TelnetAn old plain-text remote login protocol.
ThreadA task that runs beside other tasks in one program.
YAMLA simple text format for config and test files.

Commands in this lesson

12.11

Check yourself

Answer each question first, then open it to check the answer.

1Which HTTP method adds a new device to the mock API?

POST. A GET only reads the current list.

2Why must a *.pcapng file be converted before dpkt reads it?

dpkt reads the older *.pcap format. Use editcap to change the file first.

3What does paramiko.SSHClient().exec_command() return?

Three file-like objects: stdin, stdout, and stderr. Read stdout to see the command output.

4What is the difference between a running config and a startup config?

The running config is active now. The startup config loads when the device boots.

5What is the first part of a pytest test function name?

test_. pytest ignores functions that do not start with that prefix.

Practice

All commands in this chapter