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 = '172.16.2.10'
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')
sleep(.25)
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 re.search('(\\n.+?#)', response).group(0).strip().replace('#', '')
# Connect to the router using Paramiko, setup a shell to send/receive
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(peer, 22, username, password, look_for_keys=False)
except (paramiko.transport.socket.error,
paramiko.transport.SSHException,
paramiko.transport.socket.timeout,
paramiko.auth_handler.AuthenticationException):
print 'Error connecting to SSH on %s.' % peer
shell = ssh.invoke_shell()
shell.settimeout(3)
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(re.search(non_estab_states, line, re.IGNORECASE)):
continue
else:
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
ssh.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment