Foundations of Python Network Programming

(WallPaper) #1

Chapter 17 ■ Ftp


324


def main():
if len(sys.argv) != 5:
print("usage:", sys.argv[0],
" ")
exit(2)


host, username, localfile, remotedir = sys.argv[1:]
prompt = "Enter password for {} on {}: ".format(username, host)
password = getpass.getpass(prompt)


ftp = FTP(host)
ftp.login(username, password)
ftp.cwd(remotedir)
with open(localfile, 'rb') as f:
ftp.storbinary('STOR %s' % os.path.basename(localfile), f)
ftp.quit()


if name == 'main':
main()


This program looks quite similar to the earlier efforts. Because most anonymous FTP sites do not permit file
uploading, you will have to find a server somewhere to test it against; I simply installed the old, venerable ftpd on my
laptop for a few minutes and ran the test like this:


$ python binaryul.py localhost brandon test.txt /tmp


I entered my password at the prompt (brandon is my username on this machine). When the program finished,
I checked and, sure enough, a copy of the test.txt file was now sitting in /tmp. Remember not to try this over a
network to another machine, because FTP does not encrypt or protect your password!
You can modify this program to upload a file in ASCII mode by simply changing storbinary() to storlines().


Advanced Binary Uploading

Just as the download process had a complicated raw version, it is also possible to upload files manually using
ntransfercmd(), as shown in Listing 17-6.


Listing 17-6. Uploading Files a Block at a Time


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


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


import os, sys
from ftplib import FTP


def main():
if os.path.exists('linux-1.0.tar.gz'):
raise IOError('refusing to overwrite your linux-1.0.tar.gz file')

Free download pdf