对 paramiko 使用不同的密码

Using different ciphers with paramiko

如何指定不同的密码用于 paramiko ssh/sftp 连接? (类似于 scp/ssh 中的 -c 命令行)。

我试过以下代码:

    self.sshclient = paramiko.SSHClient()
    self.sshclient.load_system_host_keys()
    self.sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    self.sshclient.connect(hostname, **ssh_kwargs)

    self.transport = self.sshclient.get_transport()
    self.transport.get_security_options().ciphers = ('arcfour128',)
    self.transport.set_keepalive(keepalive)

    self.channel = self.transport.open_session()                                                                                                     
    self.channel.settimeout(timeout)

但在调试时我可以看到:

2016/02/26 15:27:47 DEBUG   Ciphers agreed: local=aes128-ctr, remote=aes128-ctr
2016/02/26 15:27:47 DEBUG   using kex diffie-hellman-group1-sha1; server key type ssh-rsa; cipher: local aes128-ctr, remote aes128-ctr; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none

我在某处读到连接应该发生在 get_security_options() 之后,反转导致我 self.transport 成为 NoneType(似乎传输与连接有关)。

SSHClient 的问题是会话是在 connect() 期间启动的,并且根据 Transport docs:

Changing the contents and/or order of these fields affects the underlying Transport (but only if you change them before starting the session).

您可以覆盖 Transport 的首选密码:

paramiko.Transport._preferred_ciphers = ('arcfour128', )
self.sshclient = paramiko.SSHClient()
self.sshclient.load_system_host_keys()
self.sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.sshclient.connect(hostname, **ssh_kwargs)
...

如果您只需要一个 SFTP 连接,您可以先创建一个 Transport,然后从该传输创建 SFTPClient 对象:

self.transport = paramiko.Transport((hostname, 22))
self.transport.get_security_options().ciphers = ('arcfour128', )
self.transport.connect(username=user, password=pass)  # or pkeys, ...
self.transport.set_keepalive(keepalive)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
self.sftp.put('local_file', 'remote_path')
self.sftp.close()