Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import paramiko
import re
from time import sleep
# Router connection details (could be read in from file or argparse)
peer = ''
username = 'admin'
password = 'admin'
def collect_output(shell, command):
""" Send command, and wait for output, looking for hostname as end
of message identifier
# Send command, but make sure there is a newline at end
shell.send(command.strip() + '\n')
output = ''
while (shell.recv_ready()):
output += shell.recv(255)
return output
def extract_hostname(shell):
""" Extract the router's hostname from the initial response """
response = collect_output(shell, 'en\nterm length 0\n')
return'(\\n.+?#)', response).group(0).strip().replace('#', '')
# Connect to the router using Paramiko, setup a shell to send/receive
ssh = paramiko.SSHClient()
ssh.connect(peer, 22, username, password, look_for_keys=False)
except (paramiko.transport.socket.error,
print 'Error connecting to SSH on %s.' % peer
shell = ssh.invoke_shell()
hostname = extract_hostname(shell)
neighbor_output = collect_output(shell, '\nshow ip bgp summ | b Neigh\n')
# Filter and add only established BGP sessions
peer_ips = []
non_estab_states = 'neighbor|idle|active|Connect|OpenSent|OpenConfirm'
for line in neighbor_output.split('\n'):
if bool(, line, re.IGNORECASE)):
ip_regex = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
peer_ips.extend(re.findall(ip_regex, line))
# Iterate through established peers and check advertised routes
for peer in peer_ips:
print 'Peer %s:' % peer
adv_output = collect_output(shell, '\nshow ip bgp neig %s advertised\n' % peer)
# Parse out prefixes in advertised routes
prefix_regex = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2})'
for prefix in re.findall(prefix_regex, adv_output):
print '\t%s' % prefix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment