【发布时间】:2013-11-11 15:45:55
【问题描述】:
我有一个创建连接的类。我可以在通道关闭之前连接并执行 1 个命令。在我拥有的另一个系统上,我可以执行多个命令并且通道不会关闭。显然这是我尝试连接的系统的配置问题。
class connect:
newconnection = ''
def __init__(self,username,password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect('somehost', username=username,password=password,port=2222,timeout=5)
except:
print "Count not connect"
sys.exit()
self.newconnection = ssh
def con(self):
return self.newconnection
然后我使用'ls'命令来打印一些输出
sshconnection = connect('someuser','somepassword').con()
stdin, stdout, stderr = sshconnection.exec_command("ls -lsa")
print stdout.readlines()
print stdout
stdin, stdout, stderr = sshconnection.exec_command("ls -lsa")
print stdout.readlines()
print stdout
sshconnection.close()
sys.exit()
在第一个 exec_command 运行后,它会打印 dir 列表的预期输出。当我在第一个 exec_command 之后打印 stdout 时,看起来通道已关闭
<paramiko.ChannelFile from <paramiko.Channel 1 (closed) -> <paramiko.Transport at 0x2400f10L (cipher aes128-ctr, 128 bits) (active; 0 open channel(s))>>>
就像我在另一个系统上所说的那样,我能够继续运行命令并且连接不会关闭。有没有办法让我保持打开状态?或者更好的方法我可以看到它关闭的原因?
编辑:所以看起来每个 SSHClient.exec_command 只能运行 1 个命令...所以我决定 get_transport().open_session() 然后运行一个命令。第一个总是有效的。第二个总是失败,脚本只是挂起
【问题讨论】:
-
您找到了很好的解决方案吗?我在输出中获得了多个 exec_command 的开放通道消息。第一个命令工作正常。问题在于随后的后续。
-
@Drt 不幸的是,看起来 exec_command 在关闭通道之前只会运行一个命令。即使我试图运行下一个命令,它也会告诉我我的频道已打开。但是该命令不会执行。我尝试了织物,它在与我尝试使用它的系统不同的系统上工作。如果您将它用于基本的 ssh 连接结构,应该会更好。或查看木偶
-
我找到了解决方案。我在打印时只使用了
stdout,忘记了我需要使用stdout.read。非常轻微的错误。你可以参考这里this is the question I raised