Listing the files in a remote FTP server

You would like to list the files available on the official Linux kernel's FTP site, ftp.kernel.org. You can select any other FTP site to try this recipe.

Getting ready

If you work on a real FTP site with a user account, you need a username and password. However, in this instance, you don't need a username (and password) with Linux kernel's FTP site as you can log in anonymously.

How to do it...

We can use the ftplib library to fetch files from our selected FTP site. A detailed documentation of this library can be found at http://docs.python.org/2/library/ftplib.html.

Let us see how we can fetch some files with ftplib.

Listing 5.1 gives a simple FTP connection test as follows:

#!/usr/bin/env python
# Python Network Programming Cookbook -- Chapter - 5
# This program is optimized for Python 2.7.
# It may run on any other version with/without modifications.

FTP_SERVER_URL = 'ftp.kernel.org'

import ftplib
def test_ftp_connection(path, username, email):
    #Open ftp connection
    ftp = ftplib.FTP(path, username, email)
    
   #List the files in the /pub directory
    ftp.cwd("/pub")
    print "File list at %s:" %path
    files = ftp.dir()
    print files

    ftp.quit()
if __name__ == '__main__':
    test_ftp_connection(path=FTP_SERVER_URL, username='anonymous',
                        email='[email protected]', 
                        )

This recipe will list the files and folders present in the FTP path, ftp.kernel.org/pub. If you run this script, you can see the following output:

$ python 5_1_list_files_on_ftp_server.py
File list at ftp.kernel.org:
drwxrwxr-x    6 ftp      ftp          4096 Dec 01  2011 dist
drwxr-xr-x   13 ftp      ftp          4096 Nov 16  2011 linux
drwxrwxr-x    3 ftp      ftp          4096 Sep 23  2008 media
drwxr-xr-x   17 ftp      ftp          4096 Jun 06  2012 scm
drwxrwxr-x    2 ftp      ftp          4096 Dec 01  2011 site
drwxr-xr-x   13 ftp      ftp          4096 Nov 27  2011 software
drwxr-xr-x    3 ftp      ftp          4096 Apr 30  2008 tools

How it works...

This recipe uses ftplib to create an FTP client session with ftp.kernel.org. The test_ftp_connection() function takes the FTP path, username, and e-mail address for connecting to the FTP server.

An FTP client session can be created by calling the FTP()function of ftplib with the preceding connection's credentials. This returns a client handle which then can be used to run the usual ftp commands, such as the command to change the working directory or cwd(). The dir()method returns the directory listing.

It is good idea to quit the FTP session by calling ftp.quit().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.17.154