Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
What the course covers
How APIs and HTTP work for network devices.
- How to call network APIs with the
requestslibrary. - How to read packet captures with Python (
dpkt) andtermshark. - 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.
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.
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.
Getting Started
Vim: press i to insert, Esc to stop, :wq to save, and :q! to quit without saving.
- tmux:
Ctrl+bthen%or"splits the screen.Ctrl+bthen an arrow key moves between panes. - Panes let you edit a script in one place and run it in another.
Software Control Management
GitHub or GitLab both work. You make an account, a repo, and a personal access token.
git add,git commit, andgit pushsend your lab code to the remote repo.- The labs use
~/mycode/for all work.
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_codechecks 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/devicesshows the device list. A POST with JSON adds a device.dpktreads*.pcapfiles. Awith 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 witheditcap -F libpcap -T ether trace.pcapng trace.pcap.editcapcomes withtshark. termshark -i logives a Wireshark-like view in the terminal. Press|to change the layout.Ctrl+cstops 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
remodule 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.
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 verand 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.DictReaderturns each row into a dict.socket.getaddrinfo()resolves a hostname to an IP. - sqlite3 is a small file database.
connect(),execute(),commit(), andclose()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")returnscomplies: TrueorFalse. - 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, thenno shutdown.
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.netifaceslists network interfaces.netifaces.interfaces()returns their names. Install it withpython3 -m pip install netifaces.telnetlibmakes 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_.assertchecks a result.pytest simpsons_test.pyruns 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 defmakes a coroutine.awaitpauses it while it waits.aiohttpsends 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 netmikoinstalls the main third-party tools.
Key commands and tools
python3 -m pip install requests dpkt paramiko netmiko pytest aiohttp netifacespython3 -m pip install --user "napalm==4.1.0"resp = requests.get("http://localhost:5000/devices")thenresp.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:latestcurl -X POST -H "Content-Type: application/json" -d '{"name": "Switch1"}' http://localhost:5000/deviceseditcap -F libpcap -T ether trace.pcapng trace.pcapsudo apt install tsharkandsudo apt install termshark -y, thensudo termshark -i lopcap = dpkt.pcap.Reader(f)thenfor ts, buf in pcap:os.system("ping -c 1 " + host)in a loop over a device listre.search(r'sip:\+(\d+)@\[(.*)\]:?(\d+)?', contact)pulls groups out of a SIP headerssh = paramiko.SSHClient()thenmykey = 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()thensftp.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")andconn.execute("CREATE TABLE ...")parser = argparse.ArgumentParser()thenparser.add_argument("--ip")andparser.parse_args()os.getenv("MYPORT", default="8888")pytest simpsons_test.pynetifaces.interfaces()lists the interface names on the hosttelnetlib.Telnet("www.python.org", 80, timeout=1)opens a Telnet clientasyncio.run(main())withasync with aiohttp.ClientSession() as session:
Key terms
The words of this course in one table. Learn them before the quiz or exam.
| Term | Meaning |
|---|---|
| API | A service that lets a program read or change data. |
| argparse | The standard module for reading command-line arguments. |
| asyncio | A single-thread way to run many waiting tasks. |
| Candidate config | A config in memory that is not active yet. |
| Coroutine | A function that can pause at await and resume. |
| eAPI | Arista's HTTP API for switches. |
| Environment variable | A value from outside the program, read with os.getenv(). |
| ICMP | The protocol behind ping. |
| Interface | A network port on a device, such as eth0. |
| NAPALM | One Python API for many network vendors. |
| Netmiko | A Python toolkit for SSH access to network devices. |
| NX-OS | Cisco's operating system for Nexus switches. |
| Paramiko | A Python library for SSH and SFTP. |
| pcap | A file that holds captured network packets. |
| pcapng | A newer packet capture format. Convert it before dpkt reads it. |
| pytest | A tool that runs Python test functions. |
| Regex | A pattern language for finding text. |
| Running config | The configuration that is active on a device now. |
| SFTP | File transfer over an SSH connection. |
| SQLite | A small database that lives in one file. |
| SSH | A secure way to log in to a remote machine. |
| Startup config | The configuration a device loads when it boots. |
| Telnet | An old plain-text remote login protocol. |
| Thread | A task that runs beside other tasks in one program. |
| YAML | A simple text format for config and test files. |
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.
Useful links
Official documentation and pages for this course.
- Alta3 Research — alta3.com
- Alta3 on YouTube — @Alta3Research
- Alta3 on GitHub — github.com/alta3