sFTP with SSH Key & Password in Python

Viewed 702

Trying to use pysftp to pull files from an sFTP server that requires both ssh key & password for authentication without much luck. Can use pysftp with just key and just password, but it breaks when I attempt to use both. Hoping someone has some experience with this. Open to using a different library if that works better.

Error output is:

paramiko.ssh_exception.BadAuthenticationType: Bad authentication type; allowed types: ['publickey']

import pysftp


connection_host = '1.1.1.1'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key'
connection_dir='/dir/on/remote/host'

with pysftp.Connection(host=connection_host, username=connection_user, password=connection_password, private_key=connection_private_key) as sftp:
    files = sftp.listdir(remotepath=connection_dir)

    for file in files:
        print("found the following file: {}".format(file))
        with sftp.cd(connection_dir):
            sftp.get(file) 
1 Answers

Working code if anyone runs into the same issue:



connection_host = '0.0.0.0'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key.pem'
connection_dir='/remote/path'


ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)

ssh.connect(connection_host, username=connection_user, password=connection_password, key_filename=connection_private_key)
sftp_client = ssh.open_sftp()

files = sftp_client.listdir(connection_dir)
sftp_client.chdir(connection_dir)

for file in files:
    print("found the following file {}".format(file))
    sftp_client.get(file,file)

if sftp_client:
    sftp_client.close()

if ssh:
    ssh.close()
Related