将Paramiko AutoAddPolicy与pysftp一起使用

gue*_*tli 5 python ssh paramiko pysftp

该代码不起作用:

def sftp_connection(self):
    import pysftp
    connection = pysftp.Connection(self.host, username=self.system_name,
                  private_key=os.path.join(HOME, '.ssh', 'id_rsa'))

    # in the next lines I try to use AutoAddPolicy
    client = connection.sftp_client()
    client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
    client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy)
    return connection
Run Code Online (Sandbox Code Playgroud)

这是例外:

def sftp_connection(self):
    import pysftp
    connection = pysftp.Connection(self.host, username=self.system_name,
                  private_key=os.path.join(HOME, '.ssh', 'id_rsa'))

    # in the next lines I try to use AutoAddPolicy
    client = connection.sftp_client()
    client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
    client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy)
    return connection
Run Code Online (Sandbox Code Playgroud)

在尝试设置之前,我得到了例外host_key_policy

我找不到通过pysftp访问客户端实例的其他方法。

有没有办法AutoAddPolicy在我得到异常之前进行设置?

还有一个相关的问题。我的问题是关于如何应用旧问题中提供的几种解决方案之一。

Mar*_*ryl 9

pysftp根本不使用Paramiko SSHClient,它使用了更底层的Transport。因此它不具有的MissingHostKeyPolicy功能SSHClient

您将必须自己实施。

一种可能的实现方式可以是:

host = 'example.com'

# Loads .ssh/known_hosts    
cnopts = CnOpts()

hostkeys = None

if cnopts.hostkeys.lookup(host) == None:
    print("New host - will accept any host key")
    # Backup loaded .ssh/known_hosts file
    hostkeys = cnopts.hostkeys
    # And do not verify host key of the new host
    cnopts.hostkeys = None

with Connection(host, username = user, private_key = pkey, cnopts = cnopts) as sftp:
    if hostkeys != None:
        print("Connected to new host, caching its hostkey")
        hostkeys.add(host, sftp.remote_server_key.get_name(), sftp.remote_server_key)
        hostkeys.save(pysftp.helpers.known_hosts())
Run Code Online (Sandbox Code Playgroud)

  • 如果 `cnopts = pysftp.CnOpts()` 将在第一次运行时[失败](https://bitbucket.org/dundeemt/pysftp/src/1c0791759688a733a558b1a25d9ae04f52cf6a64/pysftp/__init__.py?at=master#lines-64) ~/.ssh/known_hosts` 文件为空。 (2认同)