Table of Contents
A few years ago, a network engineer could get through an interview on routing protocols, subnetting and a solid troubleshooting story. That is no longer enough. Hiring managers now expect you to write a bit of Python on a whiteboard or in a shared editor, and they want to see you think about devices, not just data structures.
The good news is that interviewers rarely ask LeetCode-style puzzles here. They ask practical things: parse this show output, validate these IPs, push config to fifty switches without locking up the terminal. If you have done real automation work, you already know most of the answers. You just need to say them clearly under pressure.
Below are 20 questions that keep coming up in network automation and NetDevOps interviews, grouped from basic to production-level. Each one has a short explanation of what the interviewer is really testing and a working code sample you can adapt.
Who this is for: network engineers moving into automation roles, CCNA/CCNP holders preparing for NetDevOps interviews, and anyone who has written a few scripts but never had to defend them in front of a panel.
Part 1: Python Fundamentals for Network Data (Q1–Q5)
These open most interviews. They look simple, but interviewers watch for clean, readable code and whether you reach for the right data structure.
Q1. Write a function to check whether a string is a valid IPv4 address.
This is the classic warm-up. Many candidates split on dots and check that each part is between 0 and 255, which is fine as a first pass. The stronger answer mentions the built-in ipaddress module, because that is what you would actually use in production.
import ipaddress
def is_valid_ipv4(ip: str) -> bool:
try:
ipaddress.IPv4Address(ip)
return True
except ipaddress.AddressValueError:
return False
print(is_valid_ipv4("192.168.1.10")) # True
print(is_valid_ipv4("256.1.1.1")) # FalseWhat they are testing: do you know the standard library, and do you handle exceptions instead of letting the script crash?
If they ask you to do it without the module, show the manual version too:
def is_valid_ipv4_manual(ip: str) -> bool:
parts = ip.split(".")
if len(parts) != 4:
return False
for p in parts:
if not p.isdigit() or not 0 <= int(p) <= 255:
return False
if len(p) > 1 and p.startswith("0"): # reject leading zeros like 010
return False
return TrueQ2. Given a list of interface names, remove duplicates but keep the original order.
A set removes duplicates but loses order. Since Python 3.7, dictionaries keep insertion order, so dict.fromkeys() does the job in one line.
interfaces = ["Gi0/1", "Gi0/2", "Gi0/1", "Te1/0/1", "Gi0/2"]
unique = list(dict.fromkeys(interfaces))
print(unique) # ['Gi0/1', 'Gi0/2', 'Te1/0/1']What they are testing: whether you understand the difference between a set and an ordered collection. Saying “I’d use a set, but that loses order, so…” scores well.
Q3. Convert a subnet mask like 255.255.255.0 into CIDR prefix length.
Every network engineer can do this in their head. The point is to see if you can turn that mental model into code.
def mask_to_cidr(mask: str) -> int:
return sum(bin(int(octet)).count("1") for octet in mask.split("."))
print(mask_to_cidr("255.255.255.0")) # 24
print(mask_to_cidr("255.255.240.0")) # 20Or, the shorter standard-library route:
import ipaddress
print(ipaddress.IPv4Network("0.0.0.0/255.255.240.0").prefixlen) # 20A good follow-up to mention: the bit-counting version does not check that the mask is contiguous (255.0.255.0 would return 16). The ipaddress version will raise an error for that, which is the behaviour you want.
Q4. Build a dictionary that maps each VLAN ID to its name from this list of tuples.
vlans = [(10, "USERS"), (20, "VOICE"), (30, "MGMT"), (99, "NATIVE")]
vlan_map = {vid: name for vid, name in vlans}
print(vlan_map[20]) # VOICE
# Or simply
vlan_map = dict(vlans)The interviewer may push further: “Now give me only the VLANs above 15.” A dictionary comprehension with a condition handles that cleanly:
high_vlans = {vid: name for vid, name in vlans if vid > 15}What they are testing: comfort with comprehensions and dictionaries, which you will use constantly when handling inventory and device data.
Q5. Count how many interfaces are up, down and administratively down.
You are given a list of interface states and asked for a summary. collections. Counter is the tool here.
from collections import Counter
states = ["up", "down", "up", "administratively down", "up", "down"]
summary = Counter(states)
print(summary)
# Counter({'up': 3, 'down': 2, 'administratively down': 1})
print(summary.most_common(1)) # [('up', 3)]Candidates who write a manual loop with if key in dict are not wrong, but knowing Counter shows you have worked with real data and not just tutorials.
Part 2: Parsing and Data Handling (Q6–Q10)
Most network automation work is turning messy CLI output into structured data. Expect at least two questions from this group.
Q6. Extract all IP addresses from a block of show ip interface brief output.
import re
output = """
Interface IP-Address OK? Method Status Protocol
GigabitEthernet0/0 10.1.1.1 YES manual up up
GigabitEthernet0/1 172.16.5.1 YES manual up up
GigabitEthernet0/2 unassigned YES unset administratively down down
Loopback0 1.1.1.1 YES manual up up
"""
ips = re.findall(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", output)
print(ips) # ['10.1.1.1', '172.16.5.1', '1.1.1.1']Be ready to explain the pattern piece by piece: \d{1,3} matches one to three digits, the group repeats three times with a dot, and \b stops it from matching inside longer numbers. Then admit the regex will happily accept 999.999.999.999, so you would pass each match through ipaddress if accuracy matters.
Q7. Parse the same output into a list of dictionaries, one per interface.
This is the natural follow-up, and it separates people who have done real work from those who have not.
def parse_ip_int_brief(output: str) -> list[dict]:
results = []
for line in output.strip().splitlines()[1:]: # skip header
fields = line.split()
if len(fields) < 6:
continue
results.append({
"interface": fields[0],
"ip": fields[1],
"status": " ".join(fields[4:-1]), # handles 'administratively down'
"protocol": fields[-1],
})
return results
for intf in parse_ip_int_brief(output):
print(intf)The trap is the administratively down status, which contains a space and breaks a naive split(). Spotting that without being told is a strong signal. Then mention that in real projects you would rather use TextFSM, TTP or Genie parsers than maintain your own, because vendors change output formats between releases.
Q8. Read a CSV of devices and print only the Cisco IOS-XE routers.
import csv
# devices.csv
# hostname,ip,platform,role
# rtr-hyd-01,10.10.1.1,iosxe,router
# sw-blr-02,10.20.1.2,nxos,switch
with open("devices.csv", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
if row["platform"] == "iosxe" and row["role"] == "router":
print(row["hostname"], row["ip"])What they are testing: use of with for file handling, and DictReader so you refer to columns by name instead of index. Column positions change; names usually do not.
Q9. Load a YAML inventory file and convert it to JSON.
YAML is the standard for Ansible and Nornir inventories, while APIs speak JSON. Moving between the two is routine.
import json
import yaml # pip install pyyaml
with open("inventory.yaml") as f:
data = yaml.safe_load(f)
print(json.dumps(data, indent=2))If you say yaml.load() without a loader, expect a follow-up. Always use safe_load(), because the full loader can execute arbitrary Python objects embedded in the file. Mentioning that unprompted shows security awareness.
Q10. Given a /24 network, list all usable host IPs and check whether a given IP belongs to it.
import ipaddress
net = ipaddress.ip_network("192.168.10.0/24")
hosts = list(net.hosts())
print(hosts[0], hosts[-1]) # 192.168.10.1 192.168.10.254
print(len(hosts)) # 254
print(net.broadcast_address) # 192.168.10.255
print(ipaddress.ip_address("192.168.10.77") in net) # True
print(ipaddress.ip_address("192.168.11.5") in net) # FalseA common extension: “Split this /24 into four equal subnets.”
for subnet in net.subnets(new_prefix=26):
print(subnet)
# 192.168.10.0/26, 192.168.10.64/26, 192.168.10.128/26, 192.168.10.192/26The ipaddress module comes up so often that it is worth an hour of practice on its own before any interview.
Part 3: Device Automation Libraries (Q11–Q15)
This is where the interview shifts from Python to network automation proper. You do not need to know every library, but you should have hands-on experience with at least Netmiko and one API-based approach.
Q11. Use Netmiko to connect to a Cisco router and run show version.
from netmiko import ConnectHandler
device = {
"device_type": "cisco_ios",
"host": "10.10.1.1",
"username": "admin",
"password": "secret",
}
with ConnectHandler(**device) as conn:
output = conn.send_command("show version")
print(output)Two things interviewers look for here. First, the with block, which closes the SSH session even if something fails. Second, credentials. Hardcoding a password in a sample is fine, but say out loud that in real code you would pull it from environment variables, a vault such as HashiCorp Vault, or getpass.
Bonus points: send_command(“show version”, use_textfsm=True) returns parsed structured data instead of raw text, if the NTC templates are installed.
Q12. What is the difference between Paramiko and Netmiko?
This one is usually verbal, but have a crisp answer ready.
| Paramiko | Netmiko | |
|---|---|---|
| Layer | Low-level SSHv2 library | Built on top of Paramiko |
| Prompt handling | You manage it yourself | Handled per vendor |
| Paging (–More–) | Manual | Disabled automatically |
| Vendor support | Generic SSH | 100+ network platforms |
| Best for | Linux hosts, custom SSH work | Network device CLI automation |
A one-line summary works well: “Paramiko gives you an SSH channel. Netmiko gives you a network engineer’s SSH channel.”
Q13. Push a set of configuration commands to a device and save the config.
from netmiko import ConnectHandler
config = [
"interface Loopback100",
"description Managed by Python",
"ip address 100.100.100.1 255.255.255.255",
]
with ConnectHandler(**device) as conn:
output = conn.send_config_set(config)
output += conn.save_config()
print(output)The follow-up is almost always: “How do you know it worked?” A good answer is to run a verification show command afterwards and check for the expected line, rather than trusting that no error was printed. Mentioning a pre-change backup also helps.
Q14. Use NAPALM to get facts from devices of two different vendors.
NAPALM’s selling point is a single API across vendors. The code below works the same whether the device runs IOS or Junos.
from napalm import get_network_driver
for platform, host in [("ios", "10.10.1.1"), ("junos", "10.10.2.1")]:
driver = get_network_driver(platform)
with driver(host, "admin", "secret") as dev:
facts = dev.get_facts()
print(facts["hostname"], facts["model"], facts["os_version"])Be ready to talk about load_merge_candidate(), compare_config() and commit_config(). The ability to show a diff before committing is the main reason teams choose NAPALM for config changes.
Q15. Retrieve interface data from a device using RESTCONF with the requests library.
API-driven automation is replacing screen-scraping on modern platforms, and interviewers want to know you are not stuck in the CLI-only world.
import requests
from requests.auth import HTTPBasicAuth
url = "https://10.10.1.1/restconf/data/ietf-interfaces:interfaces"
headers = {"Accept": "application/yang-data+json"}
resp = requests.get(
url,
headers=headers,
auth=HTTPBasicAuth("admin", "secret"),
verify=False, # lab only; use a proper CA bundle in production
timeout=10,
)
resp.raise_for_status()
for intf in resp.json()["ietf-interfaces:interfaces"]["interface"]:
print(intf["name"], intf.get("enabled"))Things worth pointing out: the correct Accept header for YANG data, the timeout so the script never hangs forever, and raise_for_status() so a 401 or 404 does not get silently ignored. If you leave verify=False in, call it out as lab-only before the interviewer does.
Part 4: Scenario and Production Questions (Q16–Q20)
Senior roles spend most of the interview here. The code matters, but the reasoning around scale, failure and safety matters more.
Q16. You need to run a command on 200 devices. Your script takes 40 minutes. How do you speed it up?
The expected answer is concurrency. SSH sessions spend most of their time waiting on the network, so threads work well even with Python’s GIL.
from concurrent.futures import ThreadPoolExecutor, as_completed
from netmiko import ConnectHandler
def get_version(device: dict) -> tuple[str, str]:
with ConnectHandler(**device) as conn:
return device["host"], conn.send_command("show version | include uptime")
with ThreadPoolExecutor(max_workers=20) as pool:
futures = [pool.submit(get_version, d) for d in devices]
for fut in as_completed(futures):
host, out = fut.result()
print(f"{host}: {out}")What lifts this answer above average:
- Explaining why threads help (I/O-bound work) and when you would use multiprocessing instead (CPU-heavy parsing).
- Capping max_workers so you do not hammer TACACS/RADIUS servers or hit VTY line limits.
- Mentioning Nornir, which handles inventory, threading and results for you, as the approach you would take for a real project.
Q17. How do you handle a device that is unreachable or rejects your login, without stopping the whole run?
from netmiko import ConnectHandler
from netmiko.exceptions import (
NetmikoTimeoutException,
NetmikoAuthenticationException,
)
import logging
logging.basicConfig(filename="automation.log", level=logging.INFO)
failed = []
for device in devices:
try:
with ConnectHandler(**device) as conn:
conn.send_command("show clock")
logging.info("%s OK", device["host"])
except NetmikoTimeoutException:
logging.error("%s unreachable", device["host"])
failed.append(device["host"])
except NetmikoAuthenticationException:
logging.error("%s auth failed", device["host"])
failed.append(device["host"])
print(f"Failed devices: {failed}")Catch specific exceptions, not a bare except:. A blanket catch hides bugs in your own code. Logging to a file and producing a list of failures at the end is what operations teams actually need when the script runs overnight.
Q18. Generate interface configurations for many switches from a template.
Jinja2 is the answer nearly every time.
from jinja2 import Template
template = Template("""
{% for intf in interfaces %}
interface {{ intf.name }}
description {{ intf.desc }}
switchport access vlan {{ intf.vlan }}
{% if intf.voice %} switchport voice vlan {{ intf.voice }}
{% endif %} spanning-tree portfast
!
{% endfor %}
""")
interfaces = [
{"name": "Gi1/0/1", "desc": "Desk-101", "vlan": 10, "voice": 20},
{"name": "Gi1/0/2", "desc": "Printer", "vlan": 10, "voice": None},
]
print(template.render(interfaces=interfaces))The point to make: templates separate what a config looks like from the data that fills it. Network engineers maintain the data in YAML; the template rarely changes. That split is what makes config generation reviewable in Git.
Q19. Write a script that backs up running configs from all devices into date-stamped files.
from datetime import datetime
from pathlib import Path
from netmiko import ConnectHandler
backup_dir = Path("backups") / datetime.now().strftime("%Y-%m-%d")
backup_dir.mkdir(parents=True, exist_ok=True)
for device in devices:
with ConnectHandler(**device) as conn:
hostname = conn.find_prompt().strip("#>")
config = conn.send_command("show running-config")
(backup_dir / f"{hostname}.cfg").write_text(config)
print(f"Saved {hostname}")Nice touches to mention: using pathlib rather than string paths, taking the hostname from the prompt instead of trusting the inventory, and committing the backup folder to Git so every change shows up as a diff. Combine this with Q16 and Q17 and you have a production-grade backup job.
Q20. Check every device’s config for compliance: NTP servers must be set and Telnet must be disabled.
This question ties everything together, and it is a favourite for senior and lead roles.
import re
from pathlib import Path
backup_dir = Path("backups/2026-12-02") # folder created by the Q19 backup script
# \b stops 10.0.0.1 from also matching 10.0.0.10
REQUIRED = [r"^ntp server 10\.0\.0\.1\b", r"^ntp server 10\.0\.0\.2\b"]
# 'transport input all' enables Telnet too, so flag it as well
FORBIDDEN = [r"transport input (all|.*telnet)"]
def check_compliance(hostname: str, config: str) -> list[str]:
issues = []
for pattern in REQUIRED:
if not re.search(pattern, config, re.MULTILINE):
issues.append(f"missing: {pattern}")
for pattern in FORBIDDEN:
if re.search(pattern, config, re.MULTILINE):
issues.append(f"forbidden: {pattern}")
return issues
for cfg_file in backup_dir.glob("*.cfg"):
problems = check_compliance(cfg_file.stem, cfg_file.read_text())
status = "PASS" if not problems else "FAIL"
print(f"{cfg_file.stem:20} {status} {problems}")Strong candidates talk beyond the code. Rules should live in a YAML file so non-programmers can maintain them. Regex works for simple checks, but hierarchical config is better handled with a parser such as ciscoconfparse, so you can ask questions like “which interfaces lack a description?” Finally, the output should feed a report or a ticket, not just scroll past in a terminal.
Conclusion
Python interviews for network engineers are less about clever algorithms and more about trust. The panel wants to know whether they can hand you a script that touches production devices and sleep well that night. Clean parsing, careful error handling, sensible concurrency and a habit of verifying changes will tell them that.
Work through these 20 questions in a lab, using GNS3, EVE-NG, Cisco DevNet sandboxes or containerlab. Then try changing each one: a different vendor, a different output format, a failure you did not plan for. That kind of practice is what makes the answers come naturally on the day.
FAQs
Do network engineers need to know data structures and algorithms for these interviews?
Only the basics. Lists, dictionaries, sets, loops and simple sorting cover almost every question. Interviewers for automation roles rarely ask about trees or dynamic programming.
Which Python libraries should I learn first?
Start with ipaddress, re and Netmiko. Then add Jinja2, requests and either NAPALM or Nornir. That set covers most of what comes up in interviews and day-to-day work.
Is Ansible a replacement for Python in network automation?
No, they complement each other. Ansible is great for repeatable, declarative tasks. Python is better for custom logic, parsing and integrations. Many teams write Python modules or filters that Ansible then calls.
Which Python version should I use?
Any supported Python 3 release. Python 2 is long out of support, and some interviewers treat Python 2 syntax such as print “hello” as a red flag.
How can I practise without real hardware?
Cisco DevNet always-on sandboxes, EVE-NG, GNS3 and containerlab with vendor container images all work well. Many of the parsing questions can be practised offline with saved show command output.
Disclaimer: Code samples in this article are for learning purposes. Test them in a lab before using them on production devices.



