我想通过 sftp 下载一些早于 2 小时的文件。然后我想从网站上删除它们。我可以将以下代码用于 sftp,但在远程机器上处理对象给我带来了问题。下面的代码在“timestamp = os.stat”行失败,我认为这是一个 os 模块问题?
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()
最佳答案
虽然 OP 自己接受的答案几乎可以工作,但它的效率非常低,因为它涉及到每个文件的服务器往返。虽然实际上代码已经拥有所有需要的数据,但它只是通过使用 pysftp.Connection.listdir
将其丢弃。包装器,而不是使用 pysftp.Connection.listdir_attr
直接。
for entry in sftp.listdir_attr(remotepath):
timestamp = entry.st_mtime
createtime = datetime.datetime.fromtimestamp(timestamp)
now = datetime.datetime.now()
delta = now - createtime
if delta.hours > 2:
filepath = remotepath + '/' + entry.filename
sftp.get(filepath, os.path.join(localpath, entry.filename))
sftp.remove(filepath)
Connection.listdir
在内部检索与 Connection.listdir_attr
相同的数据。他们最终都称Paramiko SFTPClient.listdir_attr
.但是 Connection.listdir
只返回文件名,丢弃所有其他文件属性。另见 How to fetch sizes of all SFTP files in a directory through Paramiko .
但请注意,pysftp 似乎已死。考虑直接使用 Paramiko。它具有几乎相同的 API,因此上面的代码将照原样工作。另见 pysftp vs. Paramiko .
此外,不应在 SFTP 路径上使用 os.path.join
。 SFTP 始终使用正斜杠,而 os.path.join
使用本地路径语法,因此 on Windows, it would use backslashes and the code will fail .
而pysftp.Connection.get
的目标路径也需要一个文件名,而不仅仅是一个路径(这里应该使用os.path.join
)
关于Python SFTP 下载早于 x 的文件并删除网络存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12360530/