python use netmiko for embedded ssh
Table of Contents
2 description
We need a python script to auto test our boards, and we use ssh to connect the boards.
Then we found Paramiko, but Paramiko frequently raises EOF in transport thread issue.
We got the reason from:
Then netmiko comes.
It's a multi-vendor library to simplify Paramiko SSH connections to network devices.
3 install
install netmiko as below:
sudo pip install netmiko
4 netmiko sample
The netmiko sample with multiple threads support:
#!/usr/bin/env python3 import netmiko import threading import time import sys import os def ssh2(ip, username, passwd, cmd): threadname = threading.currentThread().getName() print('checking %s [%s]' % (ip, threadname)) net_connect = netmiko.ConnectHandler(device_type='cisco_ios', ip=ip, username=username, password=passwd) output = net_connect.send_command(command_string=cmd, strip_prompt=False, strip_command=False, delay_factor=5) print(output) net_connect.disconnect() if __name__=='__main__': cmd = "cat /proc/version" username = "root" passwd = "123abc" print("\n\n>>>>>>>>> Start <<<<<<<<<") threads = [] for i in range(100, 120): ip = '192.168.0.' + str(i) if os.system("ping -c 1 %s >/dev/null" % ip) == 0: a = threading.Thread(target=ssh2, args=(ip, username, passwd, cmd)) a.start() threads.append(a) time.sleep(0.5) else: print("%s not alive" % ip) for t in threads: t.join() print(">>>>>>>>> End <<<<<<<<<")
- send_command timeout max = delay_factor * 0.2 * 500
- strip_command=False, then command contained in output
- strip_prompt=False, then the board prompt contained in output