Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file from SFTP server in Python Paramiko

I am using Python Paramiko to retrieve/search file from an SFTP server. I get all file in the directory.

What I need is specific file from that directory. How do I get it?

like image 958
TTG Avatar asked Jun 09 '26 19:06

TTG


2 Answers

Use Paramiko SFTPClient.get to download a single file:

with paramiko.SSHClient() as ssh:
    ssh.connect(host, username=username, password=password)
    with ssh.open_sftp() as sftp:
        sftp.get("/remote/path/file.txt", "/local/path/file.txt")

You will also have to deal with the server's host key verification.

like image 69
Martin Prikryl Avatar answered Jun 12 '26 10:06

Martin Prikryl


Here is an answer in case you need a kind of find using a SFTP connection, not knowing the exact path and name of the file. If it is not what you were looking for, I am sorry.

I made a library named sftputil, based on paramiko, which implements advanced functionalities such as glob. To find a specific file and download it, you can do it this way :

from sftputil import SFTP

sftp = SFTP("hostname", "username", password="password")

# Here we look for a file with a name starting with `foo`
found_files = sftp.glob("directory/foo*")

# Here we look for the file `bar` in any subdirectory
found_files = sftp.glob("directory/*/bar")

# But you can use other patterns of course.

# And now the files can be downloaded
for f in found_files:
    sftp.get(f, "my/local/path")

If you don’t know glob, you should read the python documentation, as this implementation works the same way.

like image 37
RomainTT Avatar answered Jun 12 '26 10:06

RomainTT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!