思科设备的Python脚本

时间:2018-05-22 08:16:53

标签: python-2.7 scripting cisco-ios

我想从思科设备中提取运行配置,但不从代码

获取desiered输出

导入必要的模块

import time, sys, getpass, paramiko

设置脚本中使用的变量

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

使用本地身份验证为cisco交换机建立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!")

获得以下输出

  
    
      

====================== RESTART:D:\ user \ SNMP.py =============== =======       建立到10.155.111.5的交互式SSH会话

    
  

switch003# - - - - - - - - - -后 - - - - - - - - - - - - 小号

  
    

>

  

1 个答案:

答案 0 :(得分: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)