Python Network Programming FTP

Python Network Programming FTP

FTP, or File Transfer Protocol, is a well-known network protocol used to transfer files between computers on a network. It was created on a client-server architecture and can be used with user authentication. It can also be used without authentication, but this is less secure. An FTP connection maintains a current working directory and other identifiers, and each transfer requires a secondary connection over which the data is transferred. Most common web browsers can retrieve files hosted on an FTP server.

Methods in the FTP Class

In Python, we use the ftplib module, which has the following methods necessary for listing files, since we want to transfer files.

Methods Method Description
pwd() Current working directory.
cwd() Change the current working directory to path.
dir([path[,…[,cb]]) Display a directory listing for path. The optional callback cb is passed to retrlines().
storlines(cmd, f) Upload a text file using the given FTP cmd – for example, STOR filename.
storinary(cmd,f[, bs=8192]) Similar to storlines(), but for binary files.
delete(path) Delete the remote file at path.
mkd(directory) Create a remote directory.
exception ftplib.error_temp Exception raised when an error code indicating a temporary error (response codes in the 400-499 range) is received.
exception ftplib.error_perm Exception raised when an error code indicating a permanent error (response codes in the range 500-599) is received.
connect(host[, port[, timeout]] ) Connects to the given host and port. The default port number is 21, as specified by the FTP protocol.
quit() Closes the connection and exits.

Below are examples of some of the methods described above.

Listing Files

The following example uses an anonymous login to the FTP server and lists the contents of the current directory. It processes the names of the files and directories, stores them in a list, and then prints them.

import ftplib

ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

data = []

ftp.dir(data.append)

ftp.quit()

for line in data:
    print "-", line

When we run the above program, we get the following output −

- lrwxrwxrwx 1 0 0 1 Nov 13 2012 ftp -> .
- lrwxrwxrwx 1 0 0 3 Nov 13 2012 mirror -> pub
-drwxr-xr-x 23 0 0 4096 Nov 27 2017 pub
- drwxr-sr-x 88 0 450 4096 May 04 19:30 site
- drwxr-xr-x 9 0 0 4096 Jan 23 2014 vol

Changing Directory

The following program uses the cwd method in the ftplib module to change directory and then retrieve the desired content.

import ftplib

ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

data = []

ftp.cwd('/pub/') change directory to /pub/
ftp.dir(data.append)

ftp.quit()

for line in data:
    print "-", line

When we run the above program, we get the following output −

- lrwxrwxrwx 1 504 450 14 Nov 02 2007 FreeBSD -> os/BSD/FreeBSD
-lrwxrwxrwx 1 504 450 20 Nov 02 2007 ImageMagick -> graphics/ImageMagick
- lrwxrwxrwx 1 504 450 13 Nov 02 2007 NetBSD -> os/BSD/NetBSD
- lrwxrwxrwx 1 504 450 14 Nov 02 2007 OpenBSD -> os/BSD/OpenBSD
- -rw-rw-r-- 1 504 450 932 Jan 04 2015 README.nluug
- -rw-r--r-- 1 504 450 2023 May 03 2005 WhereToFindWhat.txt
- drwxr-sr-x 2 0 450 4096 Jan 26 2008 av
- drwxrwsr-x 2 0 450 4096 Aug 12 2004 comp

Retrieving Files

After obtaining the file list shown above, we can use the getfile method to retrieve a specific file. This method transfers a copy of the file from the remote system to the local system that initiated the FTP connection.

import ftplib
import sys

def getFile(ftp, filename):
try:
ftp.retrbinary("RETR " + filename, open(filename, 'wb').write)
except:
print "Error"

ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

ftp.cwd('/pub/') change directory to /pub/
getFile(ftp,'README.nluug')

ftp.quit()

When we run the above program, we find that the README.nluug file exists on the local system where the connection was initiated.

Leave a Reply

Your email address will not be published. Required fields are marked *