Search code examples
pythonsftpparamiko

Python SFTP download files older than x and delete networked storage


I'd like to download some files via sftp that are older than say 2 hours. Then I'd like to delete them from the network site. I can use the following code for sftp but handling objects on the remote machine is giving me problems. The code below fails at the 'timestamp = os.stat" line I believe it is an os module issue?

import paramiko, sys, os,time

host = 'ftp address'
port = 22
transport = paramiko.Transport((host, port))
password = "pass"                   #hard-coded
username = "user"                   #hard-coded
transport.connect(username = username, password = password)


sftp = paramiko.SFTPClient.from_transport(transport)
print 'SFTP Client initiated'

remotepath = "/remote folder/"
localpath = '/local folder/' 

for file in sftp.listdir('.'):
    fullpath   = os.path.join('.',file) 
    timestamp  = os.stat(fullpath).st_ctime # get timestamp of file
    createtime = datetime.datetime.fromtimestamp(timestamp)
    now = datetime.datetime.now()
    delta = now -createtime
    if delta.hours > 2:
        sftp.get(file,localpath) 
        sftp.remove(file)

sftp.close()
transport.close()   

Solution

  • The bit required for getting the timestamp of the file on remote machine and then comparing it to now is below. Hacked together by a non-programmer (me) but it works.

    timestamp  = sftp.stat(fullpath).st_atime  # get timestamp of file in epoch seconds
    createtime = datetime.datetime.now()
    now        = time.mktime(createtime.timetuple())
    datetime.timedelta = now - timestamp
    
    if datetime.timedelta> x:
        do something