python有关FTP及SFTP获取文件时间的操作

1、FTP获取文件时间戳

小编典典

MLST或MDTM

虽然可以使用MLST或MDTM命令通过FTP检索单个文件的时间戳,但ftplib都不支持。

当然,您可以使用实现自己的MLST或。MDTMFTP.voidcmd

有关详细信息,请参阅RFC 3659,尤其是:

一个简单的例子MDTM:

from ftplib import FTP

from dateutil import parser

# ... (connection to FTP)

timestamp = ftp.voidcmd("MDTM /remote/path/file.txt")[4:].strip()

time = parser.parse(timestamp)

print(time)

MLSD

ftplib库明确支持的唯一可以返回标准化文件时间戳记的命令是MLSD通过FTP.mlsdmethod。尽管仅当您要检索更多文件的时间戳时才使用它。

使用以下命令检索完整的目录列表 MLSD

在返回的集合中搜索所需的文件

检索modify事实

根据规范进行解析, YYYYMMDDHHMMSS[.sss]

有关详细信息,请再次参考RFC 3659,尤其是:

from ftplib import FTP

from dateutil import parser

… (connection to FTP)

files = ftp.mlsd(“/remote/path”)

for file in files:

name = file[0]

timestamp = file[1][‘modify’]

time = parser.parse(timestamp)

print(name + ‘ - ‘ + str(time))

请注意MLST,MLSD和返回的时间MDTM均为UTC(除非服务器损坏)。因此,您可能需要针对您当地的时区进行更正。

同样,请参阅RFC 3659 2.3。时间部分:

时间值始终以UTC(GMT)和公历表示,无论在服务器PI位置指示的日期和时间使用了哪种日历。

清单

如果FTP服务器不支持任何的MLST,MLSD而且MDTM,你所能做的就是用一个过时的LIST命令。这涉及解析返回的专有列表。

常见的* nix列表如下:

-rw-r--r-- 1 user group 4467 Mar 27 2018 file1.zip

-rw-r--r-- 1 user group 124529 Jun 18 15:31 file2.zip

使用这样的清单,此代码将执行以下操作:

from ftplib import FTP

from dateutil import parser

# ... (connection to FTP)

lines = []

ftp.dir("/remote/path", lines.append)

for line in lines:

tokens = line.split(maxsplit = 9)

name = tokens[8]

time_str = tokens[5] + " " + tokens[6] + " " + tokens[7]

time = parser.parse(time_str)

print(name + ' - ' + str(time))
————————————————
版权声明:本文为CSDN博主「陆贽」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_33130645/article/details/112942787

2、FTP文件定时自动下载

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
 
'''
@Time  : 2019-11-11 13:30
@Author : Peanut_C
@FileName: ftp_auto_download.py
'''
 
 
import time
from ftplib import FTP
import os
 
 
remote_path = "/xxx/yy/z/" # 远端目录
begin_time = 1500 # 任务开始时间
end_time = 1700 # 任务结束时间
 
 
today = time.strftime("%Y%m%d") # 当天日期
today_file = today + 'test.txt' # 得到当天日期的目标文件名
remote_file = remote_path + today_file # 远端文件名
local_file = '\\\\local\\' + today + '\\' + today_file # 本地文件名
log_file = 'C:\\\\log\\ftp_log.txt'
 
 
def ftp_connect():
  """用于FTP连接"""
  ftp_server = 'w.x.y.z' # ftp站点对应的IP地址
  username = 'ftpuser' # 用户名
  password = 'ftppass' # 密码
  ftp = FTP()
  ftp.set_debuglevel(0) # 较高的级别方便排查问题
  ftp.connect(ftp_server, 21)
  ftp.login(username, password)
  return ftp
 
def remote_file_exists():
  """用于FTP站点目标文件存在检测"""
  ftp = ftp_connect()
  ftp.cwd(remote_path) # 进入目标目录
  remote_file_names = ftp.nlst() # 获取文件列表
  ftp.quit()
  if today_file in remote_file_names:
    return True
  else:
    return False
 
def download_file():
  """用于目标文件下载"""
  ftp = ftp_connect()
  bufsize = 1024
  fp = open(local_file, 'wb')
  ftp.set_debuglevel(0) # 较高的级别方便排查问题
  ftp.retrbinary('RETR ' + remote_file, fp.write, bufsize)
  fp.close()
  ftp.quit()
 
 
while True:
  if int(time.strftime("%H%M")) in range(begin_time, end_time): # 判断是否在执行时间范围
    if int(time.strftime("%Y%m%d")) - int(today) == 0: # 判断是否跨日期
      while not os.path.exists(local_file): # 判断本地是否已有文件
        if remote_file_exists(): # 判断远端是否已有文件
          download_file() 
          with open(log_file, 'a') as f:
            f.write('\n' + time.strftime("%Y/%m/%d %H:%M:%S") + " 今日文件已下载!")
          time.sleep(60) # 下载完毕静默1分钟
        else:
          time.sleep(180)
          break # 注意,此处跳出循环重新判断日期,避免周末或当天没文件时陷入内层循环
      else:
        time.sleep(180)
    else:
      """如果跨日期,则根据当前日期,更新各文件日期"""
      today = time.strftime("%Y%m%d") # 当天日期
      today_file = today + 'test.txt' # 得到当天日期的目标文件名
      remote_file = remote_path + today_file # 远端文件名
      local_file = '\\\\local\\' + today + '\\' + today_file # 本地文件名
      with open(log_file, 'a') as f:
        f.write('\n' + time.strftime("%Y/%m/%d %H:%M:%S") + " 任务启动, 文件日期已更新。")
  else:
    time.sleep(1800)
3、SFTP获取文件时间戳

使用SFTP客户机的stat或{}方法获取atime/mtime/ctime

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值