Instantly share code, notes, and snippets.

Embed
What would you like to do?
s4048 ThreadPoolExecutor
#!/usr/bin/env python3
import concurrent.futures
import sys
import argparse
import time
try:
from netmiko import ConnectHandler
except ImportError:
print('Please install netmiko module: pip3 install netmiko')
raise
except:
print('Unexpected error:', sys.exc_info()[0])
raise
def process(devices):
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
hostname = {executor.submit(gethostname, device): device for device in devices}
for future in concurrent.futures.as_completed(hostname):
device = hostname[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (device, exc))
else:
print('[{}] {}'.format(device, data))
def gethostname(device):
dev = {
'device_type': 'dell_force10',
'ip': device,
'username': 'test',
'secret': 'test',
'password': 'test',
'global_delay_factor': 0,
}
device = ConnectHandler(**dev)
device.enable()
hostname = device.send_command('show run | grep hostname')
return hostname
if __name__ == '__main__':
devices = ['127.0.0.1', '10.10.10.1']
start = time.time()
process(devices)
print('Time taken = {0:.5f}'.format(time.time() - start))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment