我试图通过paramiko配置cisco路由器。
首先,我ssh到路由器,然后运行命令。但是当我连接到路由器时,我无法进入配置模式。
我的意思是路由器以用户模式连接并运行en
或conf t
不起作用!
conn = paramiko.SSHClient()
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn.connect("20.0.0.1", 22, "cisco", "123")
stdin, stdout, stderr = conn.exec_command('show ip int br')
status = stdout.channel.exit_status_ready()
if status==0:
mystring = stdout.read()
print mystring
状态为0,但mystring为空字符串。(结果为:[])
我在Fedora 20上。
由于
答案 0 :(得分:1)
您的上述命令适用于Cisco 881(即'show ip int br'正常运行并播放输出。
如果我添加第二个命令,例如'conf t'或'enable'则会失败。这是因为Cisco上的exec_command只允许一个命令。您需要运行.invoke_shell()方法来执行多个命令。
以下是一个例子:
import paramiko
from getpass import getpass
import time
ip = raw_input("Please enter your IP address: ")
username = raw_input("Please enter your username: ")
password = getpass()
remote_conn_pre=paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(ip, port=22, username=username,
password=password,
look_for_keys=False, allow_agent=False)
remote_conn = remote_conn_pre.invoke_shell()
output = remote_conn.recv(65535)
print output
remote_conn.send("show ip int brief\n")
time.sleep(.5)
output = remote_conn.recv(65535)
print output
remote_conn.send("conf t\n")
time.sleep(.5)
output = remote_conn.recv(65535)
print output
remote_conn.send("end\n")
time.sleep(.5)
output = remote_conn.recv(65535)
print output
您可能还想查看我一直在处理的这个库。它简化了一些这些机制:
答案 1 :(得分:0)
注意:确保在Cisco交换机上启用ssh。我使用了思科VIRL ISO。还要根据您的ssh更改用户名和密码。
import paramiko
import time
def attempt():
IP = "192.168.0.52"
USER = "cisco"
Password = "cisco"
PORT=22
try:
ssh = paramiko.SSHClient()
#ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(IP , port=PORT, username=USER, password=Password)
print ("Connected successfully.")
connection = ssh.invoke_shell()
connection.send("enable\n")
time.sleep(.5)
connection.send("cisco\n")
time.sleep(.5)
#connection.send("conf t\n")
connection.send("show ip int brief\n")
#connection.send("int loop 2\n")
#connection.send("ip address 2.3.1.1 255.255.255.255\n")
time.sleep(.5)
router_output = connection.recv(65535)
time.sleep(.5)
print("\n\n")
print(str(router_output) + "\n")
time.sleep(.5)
connection.send("end\n")
except paramiko.AuthenticationException:
print ("Incorrect password: "+Password)
except socket.erro:
print ("Socket Error")
except:
print("Something Went Wrong")