2

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) 
Karo
  • 61
  • 6
  • 2
    Post [Paramiko log file](https://stackoverflow.com/q/27587716/850848). + Output of `ssh -vvv ...` when successfully authenticating to the same server from the same local machine. + See [Two factor (key and keyboard-interactive) authentication to SFTP server using Python Paramiko](https://stackoverflow.com/q/56782531/850848) and [Multi-factor authentication (password and key) with Paramiko](https://stackoverflow.com/q/28837089/850848#68949359). – Martin Prikryl Feb 10 '22 at 07:09
  • @MartinPrikryl thank you VERY much. Thanks to your guidance I was able to resolve, using paramiko – Karo Feb 10 '22 at 16:11

1 Answers1

4

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()
Karo
  • 61
  • 6
  • Using `AutoAddPolicy` this way is a security flaw. See [Paramiko "Unknown Server"](https://stackoverflow.com/q/10670217/850848#43093883). – Martin Prikryl Feb 18 '22 at 20:33
  • Also it would be nice, if your question says explicitly what is the key point of your solution. I assume it was the use of the `password` and `key_filename` as per my answer at [Multi-factor authentication (password and key) with Paramiko](https://stackoverflow.com/q/28837089/850848#68949359). – Martin Prikryl Feb 18 '22 at 21:33