使用多个命令的 Python paramiko 模块

rub*_*bio 4 python ssh 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
Run Code Online (Sandbox Code Playgroud)

然后我使用'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()
Run Code Online (Sandbox Code Playgroud)

在第一个 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))>>> 
Run Code Online (Sandbox Code Playgroud)

就像我在另一个系统上所说的那样,我能够继续运行命令并且连接不会关闭。有没有办法让我保持开放?或者更好的方式我可以看到它关闭的原因?

编辑:所以看起来每个 SSHClient.exec_command 只能运行 1 个命令......所以我决定 get_transport().open_session() 然后运行一个命令。第一个总是有效的。第二个总是失败,脚本只是挂起

rub*_*bio 5

与刚刚paramiko在之后exec_command的通道被关闭,并执行所述ssh返回一个auth提示。

似乎它不可能只使用paramiko,尝试fabric或其他工具。

**fabric也没有用