使用与paramiko

时间:2016-02-26 18:08:43

标签: python 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(似乎传输与连接有关)。

1 个答案:

答案 0 :(得分:1)

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

  

更改这些字段的内容和/或顺序会影响基础传输(但前提是在开始会话之前更改它们)。

您可以做的是覆盖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()