Python Paramiko SFTP get file along with file timestamp/stat
Asked Answered
D

2

3
# 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

But I found that the date modified changed after done copy the file.

Is there anyway to copy remote file along with the file stat to the local file too ?

Disastrous answered 8/11, 2018 at 2:42 Comment(1)
Why are you using shell ls command to retrieve file a list? Use SFTP: SFTPClient.listdir.Chas
C
13

Paramiko indeed won't preserve timestamp when transferring files.

You have to explicitly call the os.utime after the download.


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

You can reuse their implementation (code simplified by me):

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

Similarly for uploads.

Chas answered 8/11, 2018 at 7:40 Comment(1)
Thanks this is what I need in my function. Because I need the date modified to process my files.Disastrous
E
1

There doesn't seem to be a way to copy with the stats documented in the paramiko SFTP module. It makes sense why though, because copying the stats besides times for a remote file wouldn't necessarily make sense (i.e. the user/group ids would not make sense on your local machine).

You can just copy the file, then get the atime/mtime/ctime using the SFTP client's stat or lstat methods and set those on the local file using os.utime.

Engulf answered 8/11, 2018 at 3:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.