Skip to content

Instantly share code, notes, and snippets.

@ovidiucs
Created July 11, 2016 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ovidiucs/a409bf80d3c7e552ebc3a2b568ac43ee to your computer and use it in GitHub Desktop.
Save ovidiucs/a409bf80d3c7e552ebc3a2b568ac43ee to your computer and use it in GitHub Desktop.
'''
Requires paramiko >=1.8.0 (paramiko had an issue with multiprocessing prior
to this)
Example code showing how to use netmiko for multiprocessing. Create a
separate process for each ssh connection. Each subprocess executes a
'show version' command on the remote device. Use a multiprocessing.queue to
pass data from subprocess to parent process.
Only supports Python2
'''
# Catch Paramiko warnings about libgmp and RandomPool
# 1. Cand se executa mai multe comenzi trebuie modifcat print output
# altfel va da too many values to unpack - done
# 2. o comanda pentru toate device-urile nu comenzi diferite pentru device-uri diferite - bad -solved
# 3. vlans dict key - random key pentru iterate (semi-done)
import warnings
with warnings.catch_warnings(record=True) as w:
import paramiko
import multiprocessing
from datetime import datetime
import netmiko
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
# DEVICE_CREDS contains the devices to connect to
from DEVICE_CREDS import all_devices
def print_output(results):
print "\nSuccessful devices:"
for a_dict in results:
for idx, val in enumerate(a_dict.items()):
t = val[1][1:]
if val[1][0]:
print '\n\n'
print '-' * 80
print 'Device = {0}\n'.format(val[0])
print ' '.join(map(str, (t)))
print '-' * 80
print "\n\nFailed devices:\n"
for a_dict in results:
for idx, val in enumerate(a_dict.items()):
if not val[1][0]:
print '\n\n'
print '-' * 80
print 'Device = {0}\n'.format(val[0])
print '-' * 80
print "\nEnd time: " + str(datetime.now())
print
def worker_show_version(a_device, mp_queue):
'''
Return a dictionary where the key is the device identifier
Value is (success|fail(boolean), return_string)
'''
try:
a_device['port']
except KeyError:
a_device['port'] = 22
identifier = '{ip}:{port}'.format(**a_device)
return_data = {}
commands = {}
send_commands = {}
if 'vlans' in a_device:
for vlans in a_device['vlans']:
commands[vlans] = 'show configuration protocols l2circuit neighbor 2.2.2.2 interface ae3.'+str(vlans)
#commands[vlans+vlans] = 'set protocols l2circuit neighbor 3.3.3.3 interface ae3.'+str(vlans)
#commands['to_config_private'] = 'show interfaces ae3.11 descriptions'
#commands['to_edit_protocol'] = 'show configuration protocols l2circuit neighbor 2.2.2.2'
#commands['show_ver_command'] = 'show interfaces ae3 descriptions'
#commands['to_top_command'] = 'show interfaces ae3.8 descriptions'
#commands['to_quit_command'] = 'show interfaces ae3.9 descriptions'
SSHClass = netmiko.ssh_dispatcher(a_device['device_type'])
net_connect = SSHClass(**a_device)
for i,v in enumerate(commands.values()):
try:
send_commands[i] = net_connect.send_command(v)
except (NetMikoTimeoutException, NetMikoAuthenticationException) as e:
return_data[identifier] = (False, e)
# Add data to the queue (for parent process)
mp_queue.put(return_data)
return None
tuple_return = tuple(send_commands.values())
return_data[identifier] = (True,) + tuple_return
mp_queue.put(return_data)
def main():
mp_queue = multiprocessing.Queue()
processes = []
print "\nStart time: " + str(datetime.now())
for a_device in all_devices:
p = multiprocessing.Process(target=worker_show_version, args=(a_device, mp_queue))
processes.append(p)
# start the work process
p.start()
# wait until the child processes have completed
for p in processes:
p.join()
# retrieve all the data from the queue
results = []
for p in processes:
results.append(mp_queue.get())
print_output(results)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment