Python Paramiko SFTP 获取文件和文件 timestamp/stat

Python Paramiko SFTP get file along with file timestamp/stat

# create SSHClient instance
ssh = paramiko.SSHClient()

list = []

# AutoAddPolicy automatically adding the hostname and new host key
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_system_host_keys()
ssh.connect(hostname, port, username, password)
stdin, stdout, stderr = ssh.exec_command("cd *path*; ls")

for i in stdout:
    list.append(i)

sftp = ssh.open_sftp()

for i in list:
    tempremote = ("*path*" + i).replace('\n', '')
    templocal = ("*path*" + i).replace('\n', '')

    try:
        #Get the file from the remote server to local directory
        sftp.get(tempremote, templocal)
    except Exception as e:
        print(e)

Remote Server File Date Modified Stat : 6/10/2018 10:00:17

Local File Date Modified Stat : Current datetime

但是我发现复制文件后修改日期变了

是否也可以将远程文件连同文件状态一起复制到本地文件?

似乎没有办法使用 paramiko SFTP 模块中记录的统计信息进行复制。这是有道理的,因为除了时间之外复制远程文件的统计数据不一定有意义(即 user/group id 在您的本地计算机上没有意义)。

您可以只复制文件,然后使用 SFTP 客户端的 statlstat 方法获取 atime/mtime/ctime,并使用 os.utime 在本地文件上设置它们。

Paramiko 在传输文件时确实不会保留时间戳。

您必须在下载后显式调用 os.utime


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

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

sftpattrs = sftp.stat(tempremote)
os.utime(templocal, (sftpattrs.st_atime, sftpattrs.st_mtime))

类似。