Use Paramiko AutoAddPolicy with pysftp

后端 未结 2 1268
孤街浪徒
孤街浪徒 2020-12-16 23:20

This code is not working:

def sftp_connection(self):
    import pysftp
    connection = pysftp.Connection(self.host, username=self.system_name,
                      


        
相关标签:
2条回答
  • 2020-12-17 00:00

    pysftp does not use Paramiko SSHClient class at all, it uses more low-level Transport class. So it does not have the MissingHostKeyPolicy functionality of SSHClient.

    You would have to implement it on your own.

    One possible implementation can be:

    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())
    
    0 讨论(0)
  • 2020-12-17 00:11

    I've implemented auto_add_key in my pysftp github fork.

    auto_add_key will add the key to known_hosts if auto_add_key=True
    Once a key is present for a host in known_hosts this key will be checked.

    Please reffer Martin Prikryl -> answer about security concerns.

    Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.

    import pysftp as sftp
    
    def push_file_to_server():
        s = sftp.Connection(host='138.99.99.129', username='root', password='pass', auto_add_key=True)
        local_path = "testme.txt"
        remote_path = "/home/testme.txt"
    
        s.put(local_path, remote_path)
        s.close()
    
    push_file_to_server()
    
    0 讨论(0)
提交回复
热议问题