我已经在这个站点和多个其他位置进行了搜索,但我无法解决在执行一条命令后连接和维护ssh会话的问题。下面是我当前的代码:
#!/opt/local/bin/python
import os
import pexpect
import paramiko
import hashlib
import StringIO
while True:
cisco_cmd = raw_input("Enter cisco router cmd:")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.221.235', username='nuts', password='cisco', timeout = 30)
stdin, stdout, stderr = ssh.exec_command(cisco_cmd)
print stdout.read()
ssh.close()
if cisco_cmd == 'exit': break我可以运行多个命令,但是对于每个命令都会创建一个新的ssh会话。上面的程序不能工作时,我需要配置模式,因为ssh会话不是reused.Any的帮助解决这个问题非常感谢。
发布于 2011-03-13 21:32:55
我使用了Exscript而不是paramiko,现在我可以在IOS设备上获得持久会话。
#!/opt/local/bin/python
import hashlib
import Exscript
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login() # Prompt the user for his name and password
conn = SSH2() # We choose to use SSH2
conn.connect('192.168.221.235') # Open the SSH connection
conn.login(account) # Authenticate on the remote host
conn.execute('conf t') # Execute the "uname -a" command
conn.execute('interface Serial1/0')
conn.execute('ip address 114.168.221.202 255.255.255.0')
conn.execute('no shutdown')
conn.execute('end')
conn.execute('sh run int Serial1/0')
print conn.response
conn.execute('show ip route')
print conn.response
conn.send('exit\r') # Send the "exit" command
conn.close() # Wait for the connection to close发布于 2011-03-09 04:38:55
您需要在while循环之外创建、连接和关闭连接。
发布于 2011-03-09 04:39:19
您的循环就是这样做的
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.221.235', username='nuts', password='cisco', timeout = 30)
while True:
cisco_cmd = raw_input("Enter cisco router cmd:")
stdin, stdout, stderr = ssh.exec_command(cisco_cmd)
print stdout.read()
if cisco_cmd == 'exit': break
ssh.close()将初始化和设置移出循环。编辑: Moved close()
https://stackoverflow.com/questions/5238000
复制相似问题