0

I am trying to delete files older than x days using below code from FTP server.

#!/usr/bin/env python
from ftplib import FTP
import time
import sys
import os
ftp_user = sys.argv[1]
ftp_pwd = sys.argv[2]
host = sys.argv[3]
def remove_files(days, dir_path):
        ftp = FTP(host)
        ftp.login(ftp_user, ftp_pwd)
        ftp.cwd(dir_path)
        now = time.time()
        for file in ftp.nlst(dir_path):
            print("filename:", file)
            #file_path =os.path.join(dir_path, f)
            if not os.path.isfile(file):
                continue
            if os.stat(file).st_mtime < now - days * 86400:
                ftp.delete(file)
                print("Deleted ", file)

I am not getting any error but files are not deleted. I think os module commands are not working in FTP server. Is there any alternative to delete the files from FTP older than x days. Basically I calling this script from ansible to automate the process.

Hmm
  • 105
  • 10
  • Does this answer your question? [Python SFTP download files older than x and delete networked storage](https://stackoverflow.com/questions/12360530/python-sftp-download-files-older-than-x-and-delete-networked-storage) – Maurice Meyer Jun 05 '20 at 08:02

1 Answers1

2

Indeed, os.path doesn't work with files over ftp.

You can use mlsd in the following manner:

ftp.mlsd(facts=["Modify"])

It'll return a list of tuples, each looking like:

('favicon.ico', {'modify': '20110616024613'})

(the first item is the file name, the second is a dictionary with the last modified time).

To get more information about each file - for example, the file's type, use:

ftp.mlsd(facts=["Modify", "Type"])

This results in data like:

('.manifest.full', {'modify': '20200423140048', 'type': 'file'})
('14.04', {'modify': '20140327184332', 'type': 'OS.unix=symlink'})
('.pool', {'modify': '20200423134557', 'type': 'dir'})
Roy2012
  • 11,755
  • 2
  • 22
  • 35
  • is there any way to check isFile or isDir using FTP? if it is file I have to delete otherwise no – Hmm Jun 05 '20 at 09:10
  • Updated the answer. Let me know if it answers your question. – Roy2012 Jun 05 '20 at 09:33
  • AttributeError: FTP instance has no attribute ''mlsd''', it seems FTP server not supporting mlsd. – Hmm Jun 06 '20 at 07:14
  • In that case, you might have to run 'dir' and parse the results. Do you need help with that? – Roy2012 Jun 06 '20 at 07:17
  • yes, can u pls help me in that. I am new to python. – Hmm Jun 06 '20 at 07:19
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/215408/discussion-between-hmm-and-roy2012). – Hmm Jun 06 '20 at 07:38
  • Are you certain you created the ftp object and logged in to the server? This error seems to indicate that the ftp object wasn't created properly. – Roy2012 Jun 07 '20 at 04:36