Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

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]







Thursday, April 7, 2011

Sauvegarde équipements réseaux via pexpect

Ci-dessous un petit script qui permet de lancer les commandes de sauvegarde TFTP via pexpect sur un composant Cisco:

import pexpect
IPa = raw_input('Entrer l adresse IP du composant:')
IP = 'ssh admin@'+IPa

child = pexpect.spawn (IP)

child.expect ('Password: ')

pwd = raw_input('Entrer le password du composant:')

print pwd

child.sendline (pwd)

child.expect ('#')

child.sendline ('copy running-config tftp:')

child.expect ('\? ')

child.sendline ('10.10.10.20')

child.expect ('\? ')

host = IPa+'.cfg'

child.sendline (host)

child.expect ('#')

child.sendline ('exit')

print child.before


Idem pour un Altéon:

import pexpect
child = pexpect.spawn ('ssh admin@10.10.10.10')
child.expect ('password: ')
child.sendline ('admin')
child.expect (['Main#','[y]'])
i = child.expect (['Main#','[y]'])
if i == 0:
print 'Connexion Ok'
elif i == 1:
child.sendline ('y')
else:
p.expect(pexpect.EOF)
print 'Timeout connexion'
child.expect ('Main#')
child.sendline ('/cfg/ptcfg')
child.expect ('server: ')
child.sendline ('10.10.10.20')
child.expect ('server: ')
child.sendline ('hostname.cfg')
child.expect ('server: ')
child.sendline ('')
print child.before


Idem pour un ISG1000:

import pexpect
child = pexpect.spawn ('ssh admin@10.10.10.10')
child.expect ('password: ')
child.sendline ('admin')
child.expect ('>')
child.sendline ('exec save config to tftp 10.10.10.20 hostname.cfg')
child.expect ('>')
print child.before


N'étant pas familié du scripting, je suis preneur de toute amélioration à apporter.