适用于 Cisco 设备的 Python 脚本

问题描述 投票:0回答:1

我想从 Cisco 设备中提取运行配置,但没有从代码中获得所需的输出

导入必要的模块

import time, sys, getpass, paramiko

设置脚本中使用的变量

ip = '10.155.111.5'
username = ""
password = ""

使用本地身份验证与思科交换机建立 SSH 会话

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

检查 SNMP 的当前设置

remote_conn.send("show run | in snmp")

显示更新的端口配置

output = remote_conn.recv(3000)
print "-------------------AFTER-----------------------"
print '\n'.join(output)

关闭 ssh 会话

sys.exit("ALL Done!")

得到以下输出

====================== 重启:D:\user\SNMP.py ================= ===== 与 10.155.111.5 建立交互式 SSH 会话

开关003# - - - - - - - - - -后 - - - - - - - - - - - -

>

python-2.7 scripting cisco-ios
1个回答
0
投票

我在 Windows 上使用 python 3.6,下面的代码适用于我,并且也应该适用于 2.6。您的路由器可能还需要启用模式的密码,因此会出现错误。尝试下面的方法,如果有效请告诉我。我还使用睡眠定时器,因为有时与遥控器的连接有点慢。

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)
© www.soinside.com 2019 - 2024. All rights reserved.