We can write a simple get
like this:
import pysftp
hostname = "somehost"
user = "bob"
password = "123456"
filename = 'somefile.txt'
with pysftp.Connection(hostname, username=user, private_key='/home/private_key_file') as sftp:
sftp.get(filename)
However, I want to specify a pattern in the filename, something like: '*.txt'
Any idea on how to do this using pysftp
?
There's no function to download files matching a file mask in pysftp.
You have to:
Connection.listdir
or Connection.walktree
(if you need recursion)Connection.get
individually for each.For a trivial implementation, see:
List files on SFTP server matching wildcard in Python using Paramiko
It's about Paramiko, but the file matching part will be the same with pysftp:
import fnmatch
for filename in sftp.listdir('/remote/path'):
if fnmatch.fnmatch(filename, "*.txt"):
sftp.get("/remote/path/" + filename, "/local/path/" + filename)
For a recursive example (you have to add the file matching), see:
Python pysftp get_r from Linux works fine on Linux but not on Windows.
See also how Connection.get_d
or Connection.get_r
are implemented.