使用多个命令的Python paramiko模块
问题内容:
我有一个创建连接的类。在关闭通道之前,我可以连接并执行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运行之后,它将输出目录列表的预期输出。当我在第一个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()然后运行一条命令。第一个始终有效。第二个总是失败并且脚本只是挂起
问题答案: