Foundations of Python Network Programming

(WallPaper) #1
Chapter 17 ■ Ftp

319


  1. The client begins listening on a new port for the data connection, and then it informs the
    server about that port.

  2. The server connects to the port that the client has opened.

  3. The file is transmitted.

  4. The data connection is closed.


This idea that the server should connect back to the client worked well in the early days of the Internet; back
then, almost every machine that could run an FTP client had a public IP address, and firewalls were relatively rare.
Today, however, the picture is more complicated. Firewalls blocking incoming connections to desktop and laptop
machines are now quite common, and many wireless, DSL, and in-house business networks do not offer client
machines real public IP addresses anyway.
To accommodate this situation, FTP also supports what is known as passive mode. In this scenario, the data
connection is made backward: the server opens an extra port, and it tells the client to make the second connection.
Other than that, everything behaves the same way.
Today, passive mode is the default with most FTP clients, including Python’s ftplib module, which I’ll explain in
this chapter.


Using FTP in Python

The Python module ftplib is the primary interface to FTP for Python programmers. It handles the details of
establishing the various connections for you, and it provides convenient ways to automate common commands.


■ Tip If you are interested only in downloading files, the urllib2 module introduced in Chapter 1 supports Ftp, and


it may be easier to use for simple downloading tasks; just run it with an ftp:// UrL. In this chapter, I describe ftplib


because it provides Ftp-specific features that are not available with urllib2.


Listing 17-1 shows a very basic ftplib example. The program connects to a remote server, displays the welcome
message, and prints the current working directory.


Listing 17-1. Making a Simple FTP Connection


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter17/connect.py


from ftplib import FTP


def main():
ftp = FTP('ftp.ibiblio.org')
print("Welcome:", ftp.getwelcome())
ftp.login()
print("Current working directory:", ftp.pwd())
ftp.quit()


if name == 'main':
main()

Free download pdf