如何使用 pysftp 仅从远程目录同步更改的文件?
How to sync only the changed files from the remote directory using pysftp?
我正在使用 pysftp 库的 get_r
函数 (https://pysftp.readthedocs.io/en/release_0.2.9/pysftp.html#pysftp.Connection.get_r) 从 sftp 服务器获取目录结构的本地副本。
当远程目录的内容发生变化并且我只想获取自上次脚本 运行 以来发生变化的文件时,这是正确的方法吗?
脚本应该能够递归同步远程目录并镜像远程目录的状态 - f.e。使用参数控制是否应删除本地过时文件(那些不再存在于远程服务器上的文件),以及是否应获取对现有文件和新文件的任何更改。
用法示例:
from sftp_sync import sync_dir
sync_dir('/remote/path/', '/local/path/')
使用 pysftp.Connection.listdir_attr
获取带有属性(包括文件时间戳)的文件列表。
然后,迭代列表并与本地文件进行比较。
import os
import pysftp
import stat
remote_path = "/remote/path"
local_path = "/local/path"
with pysftp.Connection('example.com', username='user', password='pass') as sftp:
sftp.cwd(remote_path)
for f in sftp.listdir_attr():
if not stat.S_ISDIR(f.st_mode):
print("Checking %s..." % f.filename)
local_file_path = os.path.join(local_path, f.filename)
if ((not os.path.isfile(local_file_path)) or
(f.st_mtime > os.path.getmtime(local_file_path))):
print("Downloading %s..." % f.filename)
sftp.get(f.filename, local_file_path)
虽然这些天,你不应该使用 pysftp,因为它已经死了。而是直接使用 Paramiko。见 . The above code will work with Paramiko too with its SFTPClient.listdir_attr
.
我正在使用 pysftp 库的 get_r
函数 (https://pysftp.readthedocs.io/en/release_0.2.9/pysftp.html#pysftp.Connection.get_r) 从 sftp 服务器获取目录结构的本地副本。
当远程目录的内容发生变化并且我只想获取自上次脚本 运行 以来发生变化的文件时,这是正确的方法吗?
脚本应该能够递归同步远程目录并镜像远程目录的状态 - f.e。使用参数控制是否应删除本地过时文件(那些不再存在于远程服务器上的文件),以及是否应获取对现有文件和新文件的任何更改。
用法示例:
from sftp_sync import sync_dir
sync_dir('/remote/path/', '/local/path/')
使用 pysftp.Connection.listdir_attr
获取带有属性(包括文件时间戳)的文件列表。
然后,迭代列表并与本地文件进行比较。
import os
import pysftp
import stat
remote_path = "/remote/path"
local_path = "/local/path"
with pysftp.Connection('example.com', username='user', password='pass') as sftp:
sftp.cwd(remote_path)
for f in sftp.listdir_attr():
if not stat.S_ISDIR(f.st_mode):
print("Checking %s..." % f.filename)
local_file_path = os.path.join(local_path, f.filename)
if ((not os.path.isfile(local_file_path)) or
(f.st_mtime > os.path.getmtime(local_file_path))):
print("Downloading %s..." % f.filename)
sftp.get(f.filename, local_file_path)
虽然这些天,你不应该使用 pysftp,因为它已经死了。而是直接使用 Paramiko。见 SFTPClient.listdir_attr
.