我正在使用 Python Paramiko 从 SFTP 服务器检索/搜索文件。我获取了目录中的所有文件。
我需要的是该目录中的特定文件。我怎样才能得到它?
SFTPClient.get
下载单个文件:
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")
您还必须处理服务器的主机密钥验证。
您需要做的是创建一个 ssh 客户端,然后使用管道
ls
执行 grep
来查找您的文件。如ls /srv/ftp | grep '^FTP_'
查找/srv/ftp
目录下的文件,并以FTP
开头。然后打开 sftp 连接并执行 get
命令将文件带过来。
编辑:下面的 Martin 提到有一种更好的方法来使用 SFTPClient.listdir() 获取目录内容 - 我已经修改了该方法。文档中的更多信息:https://docs.paramiko.org/en/stable/api/sftp.html
将所有这些放在一起看起来像
import paramiko
host = ''
port = 22
username = ''
password = ''
with paramiko.SSHClient() as client:
client.connect(host, port, username, password)
with client.open_sftp() as sftp:
files = sftp.listdir('/srv/ftp')
for i, file in enumerate(files):
if file and file.startswith('FTP'):
sftp.get(f'/srv/ftp/{file}', f'~/ftp/{file}')
print(f'Moved {file}')
此代码未经测试,但应该可以工作。希望这是清楚的。
如果您需要一种使用 SFTP 连接的
find
,而不知道文件的确切路径和名称,这里有一个答案。如果这不是您想要的,我很抱歉。
我基于paramiko制作了一个名为sftputil的库,它实现了
glob
等高级功能。要查找特定文件并下载它,您可以这样做:
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")
如果您不知道
glob
,您应该阅读python文档,因为此实现的工作方式相同。