Thursday, December 18, 2014

Connexion to SSH device with python and paramiko


Previously, I was using 'pexpect' in order to connect and gather information from a router or a switch.
However, I have often encountered several issues (timeout, SSH key gestion...).

It's why, now I'm using 'paramiko' (a python SSH library).
You will find below an example of the paramiko utilisation.
This script connects to a switch and returns it version.
Don't hesitate to share examples.

import paramiko
import time

username = 'user'
pwd = 'password'
cmd = 'show version \n'
ip_switch = '10.10.20.17'
remote_conn_pre=paramiko.SSHClient()
remote_conn_pre
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(ip_switch, username=username, password=pwd)
remote_conn = remote_conn_pre.invoke_shell()
time.sleep(1)
trash = remote_conn.recv(5000)
remote_conn.send(cmd)
time.sleep(2)
output = remote_conn.recv(5000)
chain = output.split()
print chain[9]







No comments:

Post a Comment