Monday 23 November 2009

Creating an FTP Script

In the last post I discussed using a web FTP service as an alternative EDI service, so I thourght I should also provide some help with FTP scripts. You can use a graphical tool like windows explorer for example by typing ftp://someserver.net in the address box. However to eliminate the work of the human operator as far as possible, scripts are needed.

That said the best first step to achieve this is to make sure you can do everything manually first. So drop to the command line. On a windows system click Start > Run, and type CMD. Now try and replicate something like the session below, the local machine prompts are in red, the ftp server responces are in blue, inputs in black.

C:\Documents and Settings\ACME>
C:\Documents and Settings\ACME>ftp ltoons.com
Connected to ltoons.com.
220 ready.
User: ACME
331 Password required for ACME.
Password:
230 User ACME logged in.

ftp> cd /outbox
250 CWD command successful.
ftp> put acme-bbunny-321.txt acme-bbunny-321.tmp
200 PORT command successful.
150 Opening ASCII mode data connection for put acme-bbunny-321.txt.
226 Transfer complete.
ftp> rename acme-bbunny-321.tmp acme-bbunny-321.txt
350 File exists, ready for destination name.
250 RNTO command successful.

ftp> cd /inbox
250 CWD command successful.
ftp> ls
200 PORT command successful.
150 Opening ASCII mode data connection for file list.
bbunny-acme-123.txt
dduck-acme-88.txt
226 Transfer complete.
ftp> get bbunny-acme-123.txt
200 PORT command successful.
150 Opening ASCII mode data connection for bbunny-acme-123.txt (999 bytes).
226 Transfer complete.
ftp> del test.tmp
250 DELE command successful.

ftp> quit
221 Goodbye.
C:\Documents and Settings\ACME>

This follows the procedure laid out in the previous post. Sending a file, listing files to be fetched and fetching them. If you can do this then you are well on your way. If not then any amount of program testing and debugging wont help you.

The next stage is some quick and dirty code just to get the job done. This example is in Python.

from ftplib import FTP

host = 'toons.com'
user = 'acme'
password = 'password'
filestosend =["acme-bbunny-321.txt"]

# Log on

ftp = FTP(host)
ftp.login(user,password)

# send

ftp.cwd('/outbox')
for filename in filestosend:
fileinput = open(filename, 'r')
ftp.storlines('STOR tempory.tmp',fileinput)
ftp.rename('tempory.tmp',filename)

# fetch

ftp.cwd('/inbox')
filestofetch = ftp.nlst()
for filename in filestofetch:
if filename[-4:] != '.tmp':
fileoutput = open(filename, 'w').write
ftp.retrlines('RETR ' + filename,fileoutput)
ftp.delete(filename)

ftp.quit()
Does this work? If it does then well done, but your work isn't finished. This script has no error traps, no try statements. The 4 variable assignments at the beginning need to be parametrised in some way. (Exercise for the reader)