与 Cisco 路由器的持久 ssh 会话
我已在此站点和多个其他位置进行搜索,但无法解决在一个命令后连接和维护 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 会话 不被重复使用。非常感谢任何解决此问题的帮助。
I have search on this site and multiple other locations but I have been unable to resolve my problem of connecting and maintaining ssh session after one command. Below is my current code:
#!/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
I can run multiple commands but for every commands a new ssh session is created.
The above program does not work when I need to configuration mode because ssh session
is not reused.Any assistance in resolving this matter is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我使用 Exscript 而不是 paramiko,现在我可以在 IOS 设备上获得持久会话。
I used Exscript instead of paramiko and I am now able to get persistent session on IOS device.
您需要在 while 循环之外创建、连接和关闭连接。
You need to create, connect and close connection outside the while loop.
您的循环将
初始化和设置移到循环之外。
编辑:移近()
Your loop does that
Move the initialisation and setup outside the loop.
EDIT: Moved close()
一旦您将
connect
和close
移出循环,您的 ssh 会话将被重用,但每个exec_command( )
发生在新的 shell 中(通过新的通道),并且是不相关的。您需要格式化命令,以便它们不需要 shell 的任何状态。如果我没记错的话,一些思科设备只允许单个执行,然后关闭连接。在这种情况下,您将需要使用
invoke_shell()
,并使用pexpect
模块(您已导入但未使用)进行交互工作。Your ssh session will be reused once you move the
connect
andclose
outside of the loop, but eachexec_command()
happens in a new shell (through a new channel), and are unrelated. You will need to format your commands so that they don't require any state from the shell.If I remember correctly, some Cisco devices only allow a single exec, and then close the connection. In that case, you will need to use
invoke_shell()
, and work interactively using thepexpect
module (which you already have imported, but aren't using).