Back to index

python3.2  3.2.2
Classes | Functions | Variables
ftplib Namespace Reference

Classes

class  Error
class  error_reply
class  error_temp
class  error_perm
class  error_proto
class  FTP
class  FTP_TLS
class  Netrc

Functions

def parse150
def parse227
def parse229
def parse257
def print_line
def ftpcp
def test

Variables

list __all__ = ["FTP","Netrc"]
int MSG_OOB = 0x1
int FTP_PORT = 21
tuple all_errors = (Error, IOError, EOFError)
string CRLF = '\r\n'
string B_CRLF = '\r\n'
 _150_re = None
 _227_re = None

Detailed Description

An FTP client class and some helper functions.

Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds

Example:

>>> from ftplib import FTP
>>> ftp = FTP('ftp.python.org') # connect to host, default port
>>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
'230 Guest login ok, access restrictions apply.'
>>> ftp.retrlines('LIST') # list directory contents
total 9
drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
-rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
'226 Transfer complete.'
>>> ftp.quit()
'221 Goodbye.'
>>>

A nice test that reveals some of the network dialogue would be:
python ftplib.py -d localhost -l -p -l

Function Documentation

def ftplib.ftpcp (   source,
  sourcename,
  target,
  targetname = '',
  type = 'I' 
)
Copy file from one FTP-instance to another.

Definition at line 900 of file ftplib.py.

00900 
00901 def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
00902     '''Copy file from one FTP-instance to another.'''
00903     if not targetname: targetname = sourcename
00904     type = 'TYPE ' + type
00905     source.voidcmd(type)
00906     target.voidcmd(type)
00907     sourcehost, sourceport = parse227(source.sendcmd('PASV'))
00908     target.sendport(sourcehost, sourceport)
00909     # RFC 959: the user must "listen" [...] BEFORE sending the
00910     # transfer request.
00911     # So: STOR before RETR, because here the target is a "user".
00912     treply = target.sendcmd('STOR ' + targetname)
00913     if treply[:3] not in {'125', '150'}: raise error_proto  # RFC 959
00914     sreply = source.sendcmd('RETR ' + sourcename)
00915     if sreply[:3] not in {'125', '150'}: raise error_proto  # RFC 959
00916     source.voidresp()
00917     target.voidresp()
00918 

Here is the call graph for this function:

def ftplib.parse150 (   resp)
Parse the '150' response for a RETR request.
Returns the expected transfer size or None; size is not guaranteed to
be present in the 150 message.

Definition at line 806 of file ftplib.py.

00806 
00807 def parse150(resp):
00808     '''Parse the '150' response for a RETR request.
00809     Returns the expected transfer size or None; size is not guaranteed to
00810     be present in the 150 message.
00811     '''
00812     if resp[:3] != '150':
00813         raise error_reply(resp)
00814     global _150_re
00815     if _150_re is None:
00816         import re
00817         _150_re = re.compile(
00818             "150 .* \((\d+) bytes\)", re.IGNORECASE | re.ASCII)
00819     m = _150_re.match(resp)
00820     if not m:
00821         return None
00822     s = m.group(1)
00823     try:
00824         return int(s)
00825     except (OverflowError, ValueError):
00826         return int(s)
00827 

Here is the call graph for this function:

Here is the caller graph for this function:

def ftplib.parse227 (   resp)
Parse the '227' response for a PASV request.
Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
Return ('host.addr.as.numbers', port#) tuple.

Definition at line 830 of file ftplib.py.

00830 
00831 def parse227(resp):
00832     '''Parse the '227' response for a PASV request.
00833     Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
00834     Return ('host.addr.as.numbers', port#) tuple.'''
00835 
00836     if resp[:3] != '227':
00837         raise error_reply(resp)
00838     global _227_re
00839     if _227_re is None:
00840         import re
00841         _227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)', re.ASCII)
00842     m = _227_re.search(resp)
00843     if not m:
00844         raise error_proto(resp)
00845     numbers = m.groups()
00846     host = '.'.join(numbers[:4])
00847     port = (int(numbers[4]) << 8) + int(numbers[5])
00848     return host, port
00849 

Here is the call graph for this function:

Here is the caller graph for this function:

def ftplib.parse229 (   resp,
  peer 
)
Parse the '229' response for a EPSV request.
Raises error_proto if it does not contain '(|||port|)'
Return ('host.addr.as.numbers', port#) tuple.

Definition at line 850 of file ftplib.py.

00850 
00851 def parse229(resp, peer):
00852     '''Parse the '229' response for a EPSV request.
00853     Raises error_proto if it does not contain '(|||port|)'
00854     Return ('host.addr.as.numbers', port#) tuple.'''
00855 
00856     if resp[:3] != '229':
00857         raise error_reply(resp)
00858     left = resp.find('(')
00859     if left < 0: raise error_proto(resp)
00860     right = resp.find(')', left + 1)
00861     if right < 0:
00862         raise error_proto(resp) # should contain '(|||port|)'
00863     if resp[left + 1] != resp[right - 1]:
00864         raise error_proto(resp)
00865     parts = resp[left + 1:right].split(resp[left+1])
00866     if len(parts) != 5:
00867         raise error_proto(resp)
00868     host = peer[0]
00869     port = int(parts[3])
00870     return host, port
00871 

Here is the call graph for this function:

Here is the caller graph for this function:

def ftplib.parse257 (   resp)
Parse the '257' response for a MKD or PWD request.
This is a response to a MKD or PWD request: a directory name.
Returns the directoryname in the 257 reply.

Definition at line 872 of file ftplib.py.

00872 
00873 def parse257(resp):
00874     '''Parse the '257' response for a MKD or PWD request.
00875     This is a response to a MKD or PWD request: a directory name.
00876     Returns the directoryname in the 257 reply.'''
00877 
00878     if resp[:3] != '257':
00879         raise error_reply(resp)
00880     if resp[3:5] != ' "':
00881         return '' # Not compliant to RFC 959, but UNIX ftpd does this
00882     dirname = ''
00883     i = 5
00884     n = len(resp)
00885     while i < n:
00886         c = resp[i]
00887         i = i+1
00888         if c == '"':
00889             if i >= n or resp[i] != '"':
00890                 break
00891             i = i+1
00892         dirname = dirname + c
00893     return dirname
00894 

Here is the caller graph for this function:

def ftplib.print_line (   line)
Default retrlines callback to print a line.

Definition at line 895 of file ftplib.py.

00895 
00896 def print_line(line):
00897     '''Default retrlines callback to print a line.'''
00898     print(line)
00899 

def ftplib.test ( )
Test program.
Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...

-d dir
-l list
-p password

Definition at line 1025 of file ftplib.py.

01025 
01026 def test():
01027     '''Test program.
01028     Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
01029 
01030     -d dir
01031     -l list
01032     -p password
01033     '''
01034 
01035     if len(sys.argv) < 2:
01036         print(test.__doc__)
01037         sys.exit(0)
01038 
01039     debugging = 0
01040     rcfile = None
01041     while sys.argv[1] == '-d':
01042         debugging = debugging+1
01043         del sys.argv[1]
01044     if sys.argv[1][:2] == '-r':
01045         # get name of alternate ~/.netrc file:
01046         rcfile = sys.argv[1][2:]
01047         del sys.argv[1]
01048     host = sys.argv[1]
01049     ftp = FTP(host)
01050     ftp.set_debuglevel(debugging)
01051     userid = passwd = acct = ''
01052     try:
01053         netrc = Netrc(rcfile)
01054     except IOError:
01055         if rcfile is not None:
01056             sys.stderr.write("Could not open account file"
01057                              " -- using anonymous login.")
01058     else:
01059         try:
01060             userid, passwd, acct = netrc.get_account(host)
01061         except KeyError:
01062             # no account for host
01063             sys.stderr.write(
01064                     "No account -- using anonymous login.")
01065     ftp.login(userid, passwd, acct)
01066     for file in sys.argv[2:]:
01067         if file[:2] == '-l':
01068             ftp.dir(file[2:])
01069         elif file[:2] == '-d':
01070             cmd = 'CWD'
01071             if file[2:]: cmd = cmd + ' ' + file[2:]
01072             resp = ftp.sendcmd(cmd)
01073         elif file == '-p':
01074             ftp.set_pasv(not ftp.passiveserver)
01075         else:
01076             ftp.retrbinary('RETR ' + file, \
01077                            sys.stdout.write, 1024)
01078     ftp.quit()
01079 


Variable Documentation

Definition at line 804 of file ftplib.py.

Definition at line 828 of file ftplib.py.

list ftplib.__all__ = ["FTP","Netrc"]

Definition at line 44 of file ftplib.py.

tuple ftplib.all_errors = (Error, IOError, EOFError)

Definition at line 64 of file ftplib.py.

Definition at line 69 of file ftplib.py.

Definition at line 68 of file ftplib.py.

Definition at line 51 of file ftplib.py.

Definition at line 47 of file ftplib.py.