'Python script for Cisco devices
I want to extract running config from Cisco devices, but not getting desiered output from the code
import the neccessary modules
import time, sys, getpass, paramiko
setup the variables used in the script
ip = '10.155.111.5'
username = ""
password = ""
establish an SSH session using local authentication to a cisco switch
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(ip, username=username, password=password,
look_for_keys= False, allow_agent=False)
print "Interactive SSH session established to %s" %ip
remote_conn = remote_conn_pre.invoke_shell()
output = remote_conn.recv(1000)
print output
check current settings on SNMP
remote_conn.send("show run | in snmp")
display the updated port config
output = remote_conn.recv(3000)
print "-------------------AFTER-----------------------"
print '\n'.join(output)
close out ssh session
sys.exit("ALL Done!")
Getting following output
====================== RESTART: D:\user\SNMP.py ====================== Interactive SSH session established to 10.155.111.5
switch003# -------------------AFTER----------------------- s
>
Solution 1:[1]
I'm using python 3.6 on Windows, the below works for me and should work in 2.6 as well. Your router probably requires a password for enable mode as well, hence the error. Try the below and let me if it works. I also use a sleep timer as sometimes the connection to the remote is a bit slow.
import time, sys, getpass, paramiko
ip = input('Please enter the IpAddress of the host:')
username = input("Please enter username:")
password = getpass.getpass('Please enter a password:')
output = ""
# Create a new instance of an sshclient
client = paramiko.SSHClient()
# Set the missing host key policy to auto add the certificate
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=ip, username=username, password=password)
remote_conn = client.invoke_shell()
print("Interactive session established with {0}\n".format(ip))
remote_conn.send('\n')
remote_conn.send('enable\n')
time.sleep(1)
en_password = password + '\n'
#Ensure you send the enable password
remote_conn.send(en_password)
time.sleep(1)
print("{0}:Getting to enable mode was a success....".format(ip))
remote_conn.send("term len 0\n")
time.sleep(1)
output = remote_conn.recv(50000)
#Flush the output
output = ""
#Send a command
remote_conn.send("sh run | i snmp\n")
#wait a couple of seconds
time.sleep(5)
output = remote_conn.recv(50000)
print(output)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pieter du Toit |
