2

I am trying to perform a task to transfer files between two different FTP locations. And the simple goal is that I would want to specific file type from FTP Location A to FTP Location B for only last few hours using Python script.

I am using ftplib to perform the task and have put together below code.

So far the file transfer is working fine for single file defined in the from_sock variable, but I am hitting road block when I am wanting to loop through all files which were created within last 2 hours and copy them. So the script I have written is basically copying individual file but I want to I wan't to move all files with particular extension example *.jpg which were created within last 2 hours. I tired to use MDTM to find the file modification time but I am not able to implement in right way.

Any help on this is much appreciated. Below is the current code:

import ftplib
srcFTP = ftplib.FTP("test.com", "username", "pass")
srcFTP.cwd("/somefolder")
desFTP = ftplib.FTP("test2.com", "username", "pass")
desFTP.cwd("/")
from_Sock = srcFTP.transfercmd("RETR Test1.text")
to_Sock = desFTP.transfercmd("STOR test1.text")
state = 0
while 1:
    block = from_Sock.recv(1024)
    if len(block) == 0:
        break
    state += len(block)
    while len(block) > 0:
        sentlen = to_Sock.send(block)
        block = block[sentlen:]     
print state, "Total Bytes Transferred"
from_Sock.close()
to_Sock.close()
srcFTP.quit()
desFTP.quit()

Thanks, DD

daaredevill
  • 31
  • 3
  • 8

1 Answers1

2

Here a short code that takes the path and uploads every file with an extension of .jpg via ftp. Its not exactly what you want but I stumbled on your answer and this might help you on your way.

import os
from ftplib import FTP

def ftpPush(filepathSource, filename, filepathDestination):
    ftp = FTP(IP, username, password)
    ftp.cwd(filepathDestination)

    ftp.storlines("STOR "+filename, open(filepathSource+filename, 'r')) 
    ftp.quit()

path = '/some/path/'
for fileName in os.listdir(path):
    if fileName.endswith(".jpg"):
        ftpPush(filepathSource=path, filename=fileName, filepathDestination='/some/destination/')

The creation time of a file can be checked on an ftp server using this example.

fileName = "nameOfFile.txt"
modifiedTime = ftp.sendcmd('MDTM ' + fileName)
# successful response: '213 20120222090254'
ftp.quit()

Now you just need to check when the file that have been modified, download it if it is below you wished for threshold and then upload them to the other computer.

SomeGuyOnAComputer
  • 5,414
  • 6
  • 40
  • 72
Edgar H
  • 1,376
  • 2
  • 17
  • 31