使用 Paramiko 保留时间戳

Preserve timestamp with Paramiko

在使用 Paramiko 将 SFTP 文件从一台服务器传输到另一台服务器时,是否有一种方法可以保留时间戳,类似于 Linux 中的 -p 参数?

原文件:

jim@vm3634:~$ ls -la
-rwxrwx---    1 jim  admin    2214 Mar 30 17:33 compcip.asc

上传的文件:

sftp> ls -la
-rwxrwx---    1 no-user  no-group    2214 Mar 30 18:49 compcip.asc

上传的文件需要与原始文件具有相同的时间戳。

Paramiko 不支持。

您必须在上传后明确调用 SFTPClient.utime


注意 pysftp (that internally uses Paramiko) supports preserving the timestamp with its pysftp.Connection.put() method.

您可以重用它们的实现(我简化的代码):

local_stat = os.stat(localpath)
times = (local_stat.st_atime, local_stat.st_mtime)

sftp.put(localpath, remotepath)

sftp.utime(remotepath, times)

类似。