home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / !Python / Lib / NetLib / py / ftplib < prev    next >
Text File  |  1996-09-30  |  16KB  |  547 lines

  1. '''An FTP client class, and some helper functions.
  2. Based on RFC 959: File Transfer Protocol
  3. (FTP), by J. Postel and J. Reynolds
  4.  
  5. Changes and improvements suggested by Steve Majewski.
  6. Modified by Jack to work on the mac.
  7. Modified by Siebren to support docstrings and PASV.
  8.  
  9.  
  10. Example:
  11.  
  12. >>> from ftplib import FTP
  13. >>> ftp = FTP('ftp.python.org') # connect to host, default port
  14. >>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname
  15. >>> ftp.retrlines('LIST') # list directory contents
  16. total 9
  17. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
  18. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
  19. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
  20. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
  21. d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
  22. drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
  23. drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
  24. drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
  25. -rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
  26. >>> ftp.quit()
  27. >>> 
  28.  
  29. A nice test that reveals some of the network dialogue would be:
  30. python ftplib.py -d localhost -l -p -l
  31. '''
  32.  
  33.  
  34. import os
  35. import sys
  36. import string
  37.  
  38. # Import SOCKS module if it exists, else standard socket module socket
  39. try:
  40.     import SOCKS; socket = SOCKS
  41. except ImportError:
  42.     import socket
  43.  
  44.  
  45. # Magic number from <socket.h>
  46. MSG_OOB = 0x1                # Process data out of band
  47.  
  48.  
  49. # The standard FTP server control port
  50. FTP_PORT = 21
  51.  
  52.  
  53. # Exception raised when an error or invalid response is received
  54. error_reply = 'ftplib.error_reply'    # unexpected [123]xx reply
  55. error_temp = 'ftplib.error_temp'    # 4xx errors
  56. error_perm = 'ftplib.error_perm'    # 5xx errors
  57. error_proto = 'ftplib.error_proto'    # response does not begin with [1-5]
  58.  
  59.  
  60. # All exceptions (hopefully) that may be raised here and that aren't
  61. # (always) programming errors on our side
  62. all_errors = (error_reply, error_temp, error_perm, error_proto, \
  63.           socket.error, IOError, EOFError)
  64.  
  65.  
  66. # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
  67. CRLF = '\r\n'
  68.  
  69.  
  70. # The class itself
  71. class FTP:
  72.  
  73.     '''An FTP client class.
  74.  
  75.     To create a connection, call the class using these argument:
  76.         host, user, passwd, acct
  77.     These are all strings, and have default value ''.
  78.     Then use self.connect() with optional host and port argument.
  79.  
  80.     To download a file, use ftp.retrlines('RETR ' + filename),
  81.     or ftp.retrbinary() with slightly different arguments.
  82.     To upload a file, use ftp.storlines() or ftp.storbinary(),
  83.     which have an open file as argument (see their definitions
  84.     below for details).
  85.     The download/upload functions first issue appropriate TYPE
  86.     and PORT or PASV commands.
  87. '''
  88.  
  89.     # Initialization method (called by class instantiation).
  90.     # Initialize host to localhost, port to standard ftp port
  91.     # Optional arguments are host (for connect()),
  92.     # and user, passwd, acct (for login())
  93.     def __init__(self, host = '', user = '', passwd = '', acct = ''):
  94.         # Initialize the instance to something mostly harmless
  95.         self.debugging = 0
  96.         self.host = ''
  97.         self.port = FTP_PORT
  98.         self.sock = None
  99.         self.file = None
  100.         self.welcome = None
  101.         if host:
  102.             self.connect(host)
  103.             if user: self.login(user, passwd, acct)
  104.  
  105.     def connect(self, host = '', port = 0):
  106.         '''Connect to host.  Arguments are:
  107.         - host: hostname to connect to (string, default previous host)
  108.         - port: port to connect to (integer, default previous port)'''
  109.         if host: self.host = host
  110.         if port: self.port = port
  111.         self.passiveserver = 0
  112.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  113.         self.sock.connect(self.host, self.port)
  114.         self.file = self.sock.makefile('rb')
  115.         self.welcome = self.getresp()
  116.  
  117.     def getwelcome(self):
  118.         '''Get the welcome message from the server.
  119.         (this is read and squirreled away by connect())'''
  120.         if self.debugging:
  121.             print '*welcome*', self.sanitize(self.welcome)
  122.         return self.welcome
  123.  
  124.     def set_debuglevel(self, level):
  125.         '''Set the debugging level.
  126.         The required argument level means:
  127.         0: no debugging output (default)
  128.         1: print commands and responses but not body text etc.
  129.         2: also print raw lines read and sent before stripping CR/LF'''
  130.         self.debugging = level
  131.     debug = set_debuglevel
  132.  
  133.     def set_pasv(self, val):
  134.         '''Use passive or active mode for data transfers.
  135.         With a false argument, use the normal PORT mode,
  136.         With a true argument, use the PASV command.'''
  137.         self.passiveserver = val
  138.  
  139.     # Internal: "sanitize" a string for printing
  140.     def sanitize(self, s):
  141.         if s[:5] == 'pass ' or s[:5] == 'PASS ':
  142.             i = len(s)
  143.             while i > 5 and s[i-1] in '\r\n':
  144.                 i = i-1
  145.             s = s[:5] + '*'*(i-5) + s[i:]
  146.         return `s`
  147.  
  148.     # Internal: send one line to the server, appending CRLF
  149.     def putline(self, line):
  150.         line = line + CRLF
  151.         if self.debugging > 1: print '*put*', self.sanitize(line)
  152.         self.sock.send(line)
  153.  
  154.     # Internal: send one command to the server (through putline())
  155.     def putcmd(self, line):
  156.         if self.debugging: print '*cmd*', self.sanitize(line)
  157.         self.putline(line)
  158.  
  159.     # Internal: return one line from the server, stripping CRLF.
  160.     # Raise EOFError if the connection is closed
  161.     def getline(self):
  162.         line = self.file.readline()
  163.         if self.debugging > 1:
  164.             print '*get*', self.sanitize(line)
  165.         if not line: raise EOFError
  166.         if line[-2:] == CRLF: line = line[:-2]
  167.         elif line[-1:] in CRLF: line = line[:-1]
  168.         return line
  169.  
  170.     # Internal: get a response from the server, which may possibly
  171.     # consist of multiple lines.  Return a single string with no
  172.     # trailing CRLF.  If the response consists of multiple lines,
  173.     # these are separated by '\n' characters in the string
  174.     def getmultiline(self):
  175.         line = self.getline()
  176.         if line[3:4] == '-':
  177.             code = line[:3]
  178.             while 1:
  179.                 nextline = self.getline()
  180.                 line = line + ('\n' + nextline)
  181.                 if nextline[:3] == code and \
  182.                     nextline[3:4] <> '-':
  183.                     break
  184.         return line
  185.  
  186.     # Internal: get a response from the server.
  187.     # Raise various errors if the response indicates an error
  188.     def getresp(self):
  189.         resp = self.getmultiline()
  190.         if self.debugging: print '*resp*', self.sanitize(resp)
  191.         self.lastresp = resp[:3]
  192.         c = resp[:1]
  193.         if c == '4':
  194.             raise error_temp, resp
  195.         if c == '5':
  196.             raise error_perm, resp
  197.         if c not in '123':
  198.             raise error_proto, resp
  199.         return resp
  200.  
  201.     def voidresp(self):
  202.         """Expect a response beginning with '2'."""
  203.         resp = self.getresp()
  204.         if resp[0] <> '2':
  205.             raise error_reply, resp
  206.  
  207.     def abort(self):
  208.         '''Abort a file transfer.  Uses out-of-band data.
  209.         This does not follow the procedure from the RFC to send Telnet
  210.         IP and Synch; that doesn't seem to work with the servers I've
  211.         tried.  Instead, just send the ABOR command as OOB data.'''
  212.         line = 'ABOR' + CRLF
  213.         if self.debugging > 1: print '*put urgent*', self.sanitize(line)
  214.         self.sock.send(line, MSG_OOB)
  215.         resp = self.getmultiline()
  216.         if resp[:3] not in ('426', '226'):
  217.             raise error_proto, resp
  218.  
  219.     def sendcmd(self, cmd):
  220.         '''Send a command and return the response.'''
  221.         self.putcmd(cmd)
  222.         return self.getresp()
  223.  
  224.     def voidcmd(self, cmd):
  225.         """Send a command and expect a response beginning with '2'."""
  226.         self.putcmd(cmd)
  227.         self.voidresp()
  228.  
  229.     def sendport(self, host, port):
  230.         '''Send a PORT command with the current host and the given port number.'''
  231.         hbytes = string.splitfields(host, '.')
  232.         pbytes = [`port/256`, `port%256`]
  233.         bytes = hbytes + pbytes
  234.         cmd = 'PORT ' + string.joinfields(bytes, ',')
  235.         self.voidcmd(cmd)
  236.  
  237.     def makeport(self):
  238.         '''Create a new socket and send a PORT command for it.'''
  239.         global nextport
  240.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  241.         sock.bind(('', 0))
  242.         sock.listen(1)
  243.         dummyhost, port = sock.getsockname() # Get proper port
  244.         host, dummyport = self.sock.getsockname() # Get proper host
  245.         resp = self.sendport(host, port)
  246.         return sock
  247.  
  248.     def transfercmd(self, cmd):
  249.         '''Initiate a transfer over the data connection.
  250.         If the transfer is active, send a port command and
  251.         the transfer command, and accept the connection.
  252.         If the server is passive, send a pasv command, connect
  253.         to it, and start the transfer command.
  254.         Either way, return the socket for the connection'''
  255.         if self.passiveserver:
  256.             host, port = parse227(self.sendcmd('PASV'))
  257.             conn = socket