Python script for IS-IS, OSPF and BGP configurations and with route redistribution
ChatGPT said:
Configuring and testing routing protocols like IS-IS, OSPF, and BGP typically
happens on network devices (routers/switches) using their CLI or APIs, not directly
via Python packets, because these protocols involve stateful exchanges, timers, and
complex logic.
However, Python scripts can help with:
Automating configuration via device APIs (e.g., NETCONF, RESTCONF, SSH)
Generating configuration files/templates
Testing protocol behavior by interacting with devices or network simulators
Parsing protocol messages if capturing with packet tools (e.g., Scapy plugins or
specialized libs)
What You Asked: Python script for protocol configurations and route redistribution
I’ll show you a practical approach using Python to:
Generate config snippets for IS-IS, OSPF, BGP including route redistribution
Automate pushing configs via SSH (using Netmiko)
Example for Cisco IOS-style configs
Step 1: Setup Python environment
Install netmiko to connect to devices:
bash
Copy
Edit
pip install netmiko
Step 2: Python script to generate and push configs for IS-IS, OSPF, BGP with
redistribution
python
Copy
Edit
from netmiko import ConnectHandler
def generate_isis_config(area, interfaces):
config = [
"router isis 1",
f"net {area}",
]
for intf in interfaces:
config.append(f"interface {intf}")
config.append("ip router isis 1")
return config
def generate_ospf_config(process_id, area, interfaces):
config = [
f"router ospf {process_id}",
f"redistribute isis",
f"redistribute bgp",
f"network 0.0.0.0 255.255.255.255 area {area}",
]
for intf in interfaces:
config.append(f"interface {intf}")
config.append(f"ip ospf {process_id} area {area}")
return config
def generate_bgp_config(as_number, neighbor_ip, neighbor_as):
config = [
f"router bgp {as_number}",
f"neighbor {neighbor_ip} remote-as {neighbor_as}",
"redistribute ospf",
"redistribute isis",
]
return config
def push_config(device, config_lines):
print(f"Connecting to {device['host']}...")
connection = ConnectHandler(**device)
output = connection.send_config_set(config_lines)
print(output)
connection.disconnect()
if __name__ == "__main__":
device = {
"device_type": "cisco_ios",
"host": "192.168.1.10",
"username": "admin",
"password": "password",
}
isis_cfg = generate_isis_config("49.0001.1921.6800.1001.00",
["GigabitEthernet0/0", "GigabitEthernet0/1"])
ospf_cfg = generate_ospf_config(1, 0, ["GigabitEthernet0/0"])
bgp_cfg = generate_bgp_config(65001, "192.168.1.20", 65002)
full_config = isis_cfg + ospf_cfg + bgp_cfg
push_config(device, full_config)
What this script does:
Generates Cisco IOS-like configs for:
IS-IS with NET address and interfaces
OSPF with redistribution of IS-IS and BGP routes
BGP with neighbor and redistribution of OSPF and IS-IS
Connects via SSH and pushes configs
Prints device output
Notes:
This is a simplified example. Real network configs will vary based on vendor and
topology.
You can adapt the script for Juniper (using device_type="juniper") or others
supported by Netmiko.
For advanced protocol testing at packet level, specialized simulators like Cisco
VIRL, GNS3, or even Scapy plugins for BGP are needed.
If you want, I can help you build scripts for:
Automated config validation
Simulating routing updates with Scapy (limited)
Parsing BGP/OSPF packets captured from live traffic
Parsing BGP/OSPF packets captured from live traffic
ChatGPT said:
Parsing BGP and OSPF packets captured from live traffic is a common task for
network protocol test engineers who want to analyze protocol behavior or
troubleshoot issues.
You can do this in Python using Scapy, which has built-in support for OSPF and some
support for BGP (though BGP support is more limited and often extended with custom
code).
Step-by-step example for parsing live BGP and OSPF packets with Scapy
1. Install Scapy
If not already installed:
bash
Copy
Edit
pip install scapy
2. Parse OSPF packets live on an interface
Here’s a simple script that sniffs packets on an interface and prints info for OSPF
packets:
python
Copy
Edit
from scapy.all import *
def ospf_packet_callback(packet):
if packet.haslayer(OSPF_Hdr):
ospf = packet[OSPF_Hdr]
print(f"OSPF Packet: Type={ospf.type}, RouterID={ospf.routerid},
AreaID={ospf.area}")
print("Sniffing for OSPF packets...")
sniff(filter="ip proto 89", prn=ospf_packet_callback, store=0, iface="eth0")
ip proto 89 filters OSPF packets.
Replace "eth0" with your interface name.
The callback prints packet type, router ID, and area ID.
3. Parse BGP packets live on an interface
Scapy doesn’t have full built-in BGP parsing, but you can capture TCP packets on
port 179 (BGP) and parse the payload manually or extend Scapy.
Here’s a simple example capturing BGP OPEN messages:
python
Copy
Edit
from scapy.all import *
BGP_PORT = 179
def bgp_packet_callback(packet):
if packet.haslayer(TCP) and (packet[TCP].dport == BGP_PORT or packet[TCP].sport
== BGP_PORT):
# Basic check for BGP message type (byte 18 in TCP payload)
payload = bytes(packet[TCP].payload)
if len(payload) > 18:
msg_type = payload[18]
bgp_types = {1: "OPEN", 2: "UPDATE", 3: "NOTIFICATION", 4: "KEEPALIVE",
5: "ROUTE-REFRESH"}
print(f"BGP Packet: Type={bgp_types.get(msg_type, 'Unknown')} from
{packet[IP].src} to {packet[IP].dst}")
print("Sniffing for BGP packets...")
sniff(filter="tcp port 179", prn=bgp_packet_callback, store=0, iface="eth0")
Captures TCP packets on port 179.
Extracts BGP message type from payload.
Prints message type and IPs.
4. Running the script
Run with root/admin privileges because sniffing needs elevated permissions.
Replace "eth0" with your actual network interface name.
You can stop with Ctrl+C.
5. Next steps for advanced parsing
For OSPF: Scapy fully supports OSPF packets, so you can dissect specific LSA types,
neighbors, etc.
For BGP: Consider using libraries like ExaBGP or BGPStream for more advanced
analysis.
Extend Scapy’s BGP layer or write your own parser for BGP message fields.
Automated config validation
ChatGPT said:
Automated config validation is a great way to ensure network device configurations
(like IS-IS, OSPF, BGP) meet your standards, contain no errors, and match intended
designs — without manually checking line-by-line.
How to Do Automated Config Validation Using Python
Common Approaches:
Pull configs from devices (via SSH/NETCONF/RESTCONF)
Parse and analyze configs using scripts
Compare against templates or expected config snippets
Check for specific config elements (e.g., route redistribution exists, proper
neighbor IPs, correct protocol parameters)
Generate validation reports
Example: Automated Validation Using Netmiko + Python
Let’s build a simple script that:
Connects to a Cisco device via SSH
Fetches running config
Checks if certain config lines (like OSPF process, route redistribution, BGP
neighbor) exist
Reports validation status
Step 1: Install required library
bash
Copy
Edit
pip install netmiko
Step 2: Python script for validation
python
Copy
Edit
from netmiko import ConnectHandler
def fetch_running_config(device):
connection = ConnectHandler(**device)
output = connection.send_command("show running-config")
connection.disconnect()
return output
def validate_config(config, checks):
results = {}
for check_name, check_strings in checks.items():
found = all(any(line.strip().startswith(cs) for line in
config.splitlines()) for cs in check_strings)
results[check_name] = found
return results
if __name__ == "__main__":
device = {
"device_type": "cisco_ios",
"host": "192.168.1.10",
"username": "admin",
"password": "password",
"secret": "", # Enable password if needed
}
checks = {
"OSPF Configured": ["router ospf"],
"Route Redistribution": ["redistribute ospf", "redistribute bgp"],
"BGP Neighbor": ["neighbor 192.168.1.20 remote-as"],
}
config = fetch_running_config(device)
validation_results = validate_config(config, checks)
for check, passed in validation_results.items():
status = "PASS" if passed else "FAIL"
print(f"{check}: {status}")
How This Works:
fetch_running_config() connects to device and grabs full config.
validate_config() checks if all strings in each validation check appear in config
lines.
Reports PASS/FAIL for each validation item.
How to Extend This:
Use regular expressions for more flexible matching.
Validate config syntax and parameter values.
Compare running config to a golden template line-by-line.
Generate HTML or CSV reports.
Integrate with CI/CD pipelines for automatic validation.
Use NAPALM library for multi-vendor support and config parsing.
Simulating routing updates with Scapy (limited)
ChatGPT said:
Sure! Simulating routing protocol updates like BGP, OSPF, or IS-IS with Scapy is
possible but limited because these protocols are complex, stateful, and involve
many message types and timers.
Still, Scapy can be used to craft and send simplified routing protocol packets to
test how devices react or to capture/analyze responses.
What you can do with Scapy for Routing Updates
Craft and send BGP OPEN, UPDATE, KEEPALIVE messages (basic)
Send OSPF Hello or LSA packets
Send IS-IS Hello (IIH) or LSP PDUs
Sniff and analyze routing messages on the network
Test basic interoperability or fuzz malformed packets
Example: Crafting and sending a basic BGP OPEN message with Scapy
python
Copy
Edit
from scapy.all import *
from scapy.contrib.bgp import *
def send_bgp_open(dst_ip):
# BGP Open message fields
bgp_open = BGPHeader(type=1) / BGPOpen(version=4, my_as=65001, hold_time=90,
bgp_id="1.1.1.1")
# Build TCP packet with BGP port 179
ip = IP(dst=dst_ip)
tcp = TCP(sport=RandShort(), dport=179, flags='S', seq=1000)
# Send SYN to start TCP handshake (simplified - no ACK)
send(ip/tcp)
# Here, ideally, you’d complete TCP handshake before sending BGP Open.
# For simplicity, send BGP Open in a TCP packet (won’t establish full session)
tcp.flags = 'PA' # PSH+ACK flags for data packet
tcp.seq = 1001
packet = ip/tcp/bgp_open
send(packet)
print(f"Sent BGP OPEN to {dst_ip}")
if __name__ == "__main__":
send_bgp_open("192.168.1.2")
Note: This script is very simplified. Real BGP requires a full TCP handshake,
proper sequence numbers, ACKs, and session states.
Example: Crafting and sending a basic OSPF Hello packet
python
Copy
Edit
from scapy.all import *
from scapy.contrib.ospf import *
def send_ospf_hello(dst_ip, iface):
ip = IP(src=get_if_addr(iface), dst=dst_ip)
ospf_hello = OSPF_Hdr(type=1, routerid=get_if_addr(iface), area=0) /
OSPF_Hello()
packet = ip / ospf_hello
send(packet, iface=iface)
print(f"Sent OSPF Hello to {dst_ip} on {iface}")
if __name__ == "__main__":
send_ospf_hello("224.0.0.5", "eth0") # 224.0.0.5 is all OSPF routers multicast
Limitations:
No built-in state machine (TCP handshake, BGP FSM).
Sequence numbers, timers, session handling need manual coding.
Realistic routing update simulation usually requires dedicated simulators (e.g.,
GNS3, Cisco VIRL, ExaBGP).
Useful mostly for testing specific message handling, fuzzing, or lightweight
interaction.
Suggest routing simulators that integrate with Python.
ChatGPT said:
Absolutely! Here are some popular routing/network simulators that can integrate
with Python, allowing you to automate, test, and interact programmatically with
routing protocols like BGP, OSPF, IS-IS, and more:
1. GNS3 (Graphical Network Simulator 3)
What: A powerful network emulator that runs real Cisco IOS, Juniper JunOS, and many
other images.
Python Integration: GNS3 has a REST API you can control via Python scripts to
start/stop devices, push configs, and collect data.
Use Case: Automate labs, test protocol behaviors on real OS images.
Learn More: https://gns3.com/
2. Cisco VIRL / CML (Cisco Modeling Labs)
What: Cisco’s official network simulation/emulation platform for Cisco devices.
Python Integration: Offers a robust REST API and SDK for automation.
Use Case: Realistic network topologies with Cisco IOS, IOS-XE, NX-OS, etc.
Learn More: https://learningnetwork.cisco.com/s/virl
3. EVE-NG (Emulated Virtual Environment - Next Generation)
What: Multi-vendor network emulator, supports many vendor images.
Python Integration: REST API available for automation.
Use Case: Complex labs, multi-vendor scenarios.
Learn More: https://www.eve-ng.net/
4. ExaBGP
What: Not a full network simulator but a powerful BGP route injector written in
Python.
Python Integration: Native Python API to send/receive BGP updates, simulate BGP
speakers.
Use Case: Simulate BGP neighbors and test BGP route policies.
Learn More: https://github.com/Exa-Networks/exabgp
5. Mininet
What: Lightweight network emulator primarily for SDN/OpenFlow.
Python Integration: Written in Python, fully programmable via Python scripts.
Use Case: Simulate network topologies, test routing with real Linux routing
daemons.
Learn More: http://mininet.org/
6. FRRouting (FRR) with Docker + Python
What: Open-source routing suite supporting BGP, OSPF, IS-IS, etc.
Python Integration: Run FRR in containers, automate config and tests using Python
scripts (via SSH/REST).
Use Case: Build test labs with real routing protocols and full control.
Learn More: https://frrouting.org/
Bonus: Protocol-Specific Libraries
PyBGPStream (for BGP data analysis)
Scapy with contrib modules (limited packet crafting/sniffing)
Summary Table
Simulator Protocols Supported Python Integration Use Case
GNS3 Any real device images REST API + Python client Full device emulation
Cisco VIRL/CML Cisco protocols REST API + SDK Cisco-centric labs
EVE-NG Multi-vendor REST API Complex multi-vendor emulation
ExaBGP BGP only Native Python API BGP neighbor simulation
Mininet Linux-based routing Native Python scripting SDN + lightweight
routing labs
FRRouting + Docker BGP, OSPF, IS-IS, etc. SSH/REST + Python Real routing stack
in containers
If you want, I can help you get started with any of these—like writing Python
scripts to automate GNS3, or building a BGP simulator with ExaBGP. Just let me
know!