Python SFTP 下载早于 x 的文件并删除网络存储 [英] Python SFTP download files older than x and delete networked storage

查看:45
本文介绍了Python SFTP 下载早于 x 的文件并删除网络存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 sftp 下载一些早于 2 小时的文件.然后我想从网站上删除它们.我可以将以下代码用于 sftp,但在远程机器上处理对象给我带来了问题.下面的代码在timestamp = os.stat"行失败,我认为这是 os 模块问题?

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()   

推荐答案

获取远程机器上文件的时间戳并将其与现在进行比较所需的位如下.被一个非程序员(我)破解,但它有效.

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

这篇关于Python SFTP 下载早于 x 的文件并删除网络存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆