Using ftplib in Python 3

This script download files with timestamp less than argv[1] days old.

#!/usr/bin/python3

from ftplib import FTP
import datetime
from sys import argv

url = ("url")
user = ("anonymous")
password = ("anonymous")

today = datetime.date.today()

ftp = FTP(url)
fs = ftp.login(user, password)
print (fs)
fs = ftp.makepasv()
print (fs)
# Change directory
fs = ftp.cwd("/pub/")
print (fs)

# List directory and storing in varibale "lines".
lines = []
fs = ftp.retrlines('LIST', lines.append)
print (lines)

# Excluding directories from varibale "lines".
list = []
for line in lines:
    if str("d") not in line[0]:
        sline = line.split()
        list.append(sline)
print (list)

# Download only files less than argv[1] days old.
for file in list:
    for daysago in range(int(argv[1])):
        date = today - datetime.timedelta(days=daysago)
        ftpdate = date.strftime("['%b', '%d']")
        if str(ftpdate) == str(file[5:7]):
            ftp.retrbinary("RETR " + file[8], open(file[8], 'wb').write)

Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: