09.11.2016 Views

Foundations of Python Network Programming 978-1-4302-3004-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 17 ■ FTP<br />

f.login()<br />

print "Current working directory:", f.pwd()<br />

f.quit()<br />

The welcome message will generally have no information that could be usefully parsed by your<br />

program, but you might want to display it if a user is calling your client interactively. The login()<br />

function can take several parameters, including a username, password, and a third, rarely used<br />

authentication token that FTP calls an “account.” Here we have called it without parameters, which<br />

makes it log in as the user “anonymous” with a generic value for the password.<br />

Recall that an FTP session can visit different directories, just like a shell prompt can move between<br />

locations with cd. Here, the pwd() function returns the current working directory on the remote site <strong>of</strong><br />

the connection. Finally, the quit() function logs out and closes the connection.<br />

Here is what the program outputs when run:<br />

$ ./connect.py<br />

Welcome: 220 ProFTPD Server (Bring it on...)<br />

Current working directory: /<br />

ASCII and Binary Files<br />

When making an FTP transfer, you have to decide whether you want the file treated as a monolithic<br />

block <strong>of</strong> binary data, or whether you want it parsed as a text file so that your local machine can paste its<br />

lines back together using whatever end-<strong>of</strong>-line character is native to your platform.<br />

A file transferred in so-called “ASCII mode” is delivered one line at a time, so that you can glue the<br />

lines back together on the local machine using its own line-ending convention. Take a look at Listing 17–<br />

2 for a <strong>Python</strong> program that downloads a well-known text file and saves it in your local directory.<br />

Listing 17–2. Downloading an ASCII File<br />

#!/usr/bin/env python<br />

# ASCII download - Chapter 17 - asciidl.py<br />

# Downloads README from remote and writes it to disk.<br />

import os<br />

from ftplib import FTP<br />

if os.path.exists('README'):<br />

» raise IOError('refusing to overwrite your README file')<br />

def writeline(data):<br />

» fd.write(data)<br />

» fd.write(os.linesep)<br />

f = FTP('ftp.kernel.org')<br />

f.login()<br />

f.cwd('/pub/linux/kernel')<br />

fd = open('README', 'w')<br />

f.retrlines('RETR README', writeline)<br />

fd.close()<br />

f.quit()<br />

294

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!