home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Applications / Python 1.3 / Python 1.3 PPC / Lib / ftplib.py < prev    next >
Encoding:
Python Source  |  1995-10-11  |  12.8 KB  |  462 lines  |  [TEXT/PYTH]

  1. # An FTP client class.  Based on RFC 959: File Transfer Protocol
  2. # (FTP), by J. Postel and J. Reynolds
  3.  
  4. # Changes and improvements suggested by Steve Majewski
  5. # Modified by Jack to work on the mac.
  6.  
  7.  
  8. # Example:
  9. #
  10. # >>> from ftplib import FTP
  11. # >>> ftp = FTP('ftp.python.org') # connect to host, default port
  12. # >>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname
  13. # >>> ftp.retrlines('LIST') # list directory contents
  14. # total 9
  15. # drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
  16. # drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
  17. # drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
  18. # drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
  19. # d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
  20. # drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
  21. # drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
  22. # drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
  23. # -rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
  24. # >>> ftp.quit()
  25. # >>> 
  26. #
  27. # To download a file, use ftp.retrlines('RETR ' + filename),
  28. # or ftp.retrbinary() with slightly different arguments.
  29. # To upload a file, use ftp.storlines() or ftp.storbinary(), which have
  30. # an open file as argument (see their definitions below for details).
  31. # The download/upload functions first issue appropriate TYPE and PORT
  32. # commands.
  33.  
  34.  
  35. import os
  36. import sys
  37. import string
  38.  
  39. # Import SOCKS module if it exists, else standard socket module socket
  40. try:
  41.     import SOCKS; socket = SOCKS
  42. except ImportError:
  43.     import socket
  44.  
  45.  
  46. # Magic number from <socket.h>
  47. MSG_OOB = 0x1                # Process data out of band
  48.  
  49.  
  50. # The standard FTP server control port
  51. FTP_PORT = 21
  52.  
  53.  
  54. # Exception raised when an error or invalid response is received
  55. error_reply = 'ftplib.error_reply'    # unexpected [123]xx reply
  56. error_temp = 'ftplib.error_temp'    # 4xx errors
  57. error_perm = 'ftplib.error_perm'    # 5xx errors
  58. error_proto = 'ftplib.error_proto'    # response does not begin with [1-5]
  59.  
  60.  
  61. # All exceptions (hopefully) that may be raised here and that aren't
  62. # (always) programming errors on our side
  63. all_errors = (error_reply, error_temp, error_perm, error_proto, \
  64.           socket.error, IOError, EOFError)
  65.  
  66.  
  67. # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
  68. CRLF = '\r\n'
  69.  
  70.  
  71. # The class itself
  72. class FTP:
  73.  
  74.     # New initialization method (called by class instantiation)
  75.     # Initialize host to localhost, port to standard ftp port
  76.     # Optional arguments are host (for connect()),
  77.     # and user, passwd, acct (for login())
  78.     def __init__(self, host = '', user = '', passwd = '', acct = ''):
  79.         # Initialize the instance to something mostly harmless
  80.         self.debugging = 0
  81.         self.host = ''
  82.         self.port = FTP_PORT
  83.         self.sock = None
  84.         self.file = None
  85.         self.welcome = None
  86.         if host:
  87.             self.connect(host)
  88.             if user: self.login(user, passwd, acct)
  89.  
  90.     # Connect to host.  Arguments:
  91.     # - host: hostname to connect to (default previous host)
  92.     # - port: port to connect to (default previous port)
  93.     def connect(self, host = '', port = 0):
  94.         if host: self.host = host
  95.         if port: self.port = port
  96.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  97.         self.sock.connect(self.host, self.port)
  98.         self.file = self.sock.makefile('r')
  99.         self.welcome = self.getresp()
  100.  
  101.     # Get the welcome message from the server
  102.     # (this is read and squirreled away by connect())
  103.     def getwelcome(self):
  104.         if self.debugging:
  105.             print '*welcome*', self.sanitize(self.welcome)
  106.         return self.welcome
  107.  
  108.     # Set the debugging level.  Argument level means:
  109.     # 0: no debugging output (default)
  110.     # 1: print commands and responses but not body text etc.
  111.     # 2: also print raw lines read and sent before stripping CR/LF
  112.     def set_debuglevel(self, level):
  113.         self.debugging = level
  114.     debug = set_debuglevel
  115.  
  116.     # Internal: "sanitize" a string for printing
  117.     def sanitize(self, s):
  118.         if s[:5] == 'pass ' or s[:5] == 'PASS ':
  119.             i = len(s)
  120.             while i > 5 and s[i-1] in '\r\n':
  121.                 i = i-1
  122.             s = s[:5] + '*'*(i-5) + s[i:]
  123.         return `s`
  124.  
  125.     # Internal: send one line to the server, appending CRLF
  126.     def putline(self, line):
  127.         line = line + CRLF
  128.         if self.debugging > 1: print '*put*', self.sanitize(line)
  129.         self.sock.send(line)
  130.  
  131.     # Internal: send one command to the server (through putline())
  132.     def putcmd(self, line):
  133.         if self.debugging: print '*cmd*', self.sanitize(line)
  134.         self.putline(line)
  135.  
  136.     # Internal: return one line from the server, stripping CRLF.
  137.     # Raise EOFError if the connection is closed
  138.     def getline(self):
  139.         line = self.file.readline()
  140.         if self.debugging > 1:
  141.             print '*get*', self.sanitize(line)
  142.         if not line: raise EOFError
  143.         if line[-2:] == CRLF: line = line[:-2]
  144.         elif line[-1:] in CRLF: line = line[:-1]
  145.         return line
  146.  
  147.     # Internal: get a response from the server, which may possibly
  148.     # consist of multiple lines.  Return a single string with no
  149.     # trailing CRLF.  If the response consists of multiple lines,
  150.     # these are separated by '\n' characters in the string
  151.     def getmultiline(self):
  152.         line = self.getline()
  153.         if line[3:4] == '-':
  154.             code = line[:3]
  155.             while 1:
  156.                 nextline = self.getline()
  157.                 line = line + ('\n' + nextline)
  158.                 if nextline[:3] == code and \
  159.                     nextline[3:4] <> '-':
  160.                     break
  161.         return line
  162.  
  163.     # Internal: get a response from the server.
  164.     # Raise various errors if the response indicates an error
  165.     def getresp(self):
  166.         resp = self.getmultiline()
  167.         if self.debugging: print '*resp*', self.sanitize(resp)
  168.         self.lastresp = resp[:3]
  169.         c = resp[:1]
  170.         if c == '4':
  171.             raise error_temp, resp
  172.         if c == '5':
  173.             raise error_perm, resp
  174.         if c not in '123':
  175.             raise error_proto, resp
  176.         return resp
  177.  
  178.     # Expect a response beginning with '2'
  179.     def voidresp(self):
  180.         resp = self.getresp()
  181.         if resp[0] <> '2':
  182.             raise error_reply, resp
  183.  
  184.     # Abort a file transfer.  Uses out-of-band data.
  185.     # This does not follow the procedure from the RFC to send Telnet
  186.     # IP and Synch; that doesn't seem to work with the servers I've
  187.     # tried.  Instead, just send the ABOR command as OOB data.
  188.     def abort(self):
  189.         line = 'ABOR' + CRLF
  190.         if self.debugging > 1: print '*put urgent*', self.sanitize(line)
  191.         self.sock.send(line, MSG_OOB)
  192.         resp = self.getmultiline()
  193.         if resp[:3] not in ('426', '226'):
  194.             raise error_proto, resp
  195.  
  196.     # Send a command and return the response
  197.     def sendcmd(self, cmd):
  198.         self.putcmd(cmd)
  199.         return self.getresp()
  200.  
  201.     # Send a command and expect a response beginning with '2'
  202.     def voidcmd(self, cmd):
  203.         self.putcmd(cmd)
  204.         self.voidresp()
  205.  
  206.     # Send a PORT command with the current host and the given port number
  207.     def sendport(self, host, port):
  208.         hbytes = string.splitfields(host, '.')
  209.         pbytes = [`port/256`, `port%256`]
  210.         bytes = hbytes + pbytes
  211.         cmd = 'PORT ' + string.joinfields(bytes, ',')
  212.         self.voidcmd(cmd)
  213.  
  214.     # Create a new socket and send a PORT command for it
  215.     def makeport(self):
  216.         global nextport
  217.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  218.         sock.bind(('', 0))
  219.         sock.listen(1)
  220.         dummyhost, port = sock.getsockname() # Get proper port
  221.         host, dummyport = self.sock.getsockname() # Get proper host
  222.         resp = self.sendport(host, port)
  223.         return sock
  224.  
  225.     # Send a port command and a transfer command, accept the connection
  226.     # and return the socket for the connection
  227.     def transfercmd(self, cmd):
  228.         sock = self.makeport()
  229.         resp = self.sendcmd(cmd)
  230.         if resp[0] <> '1':
  231.             raise error_reply, resp
  232.         conn, sockaddr = sock.accept()
  233.         return conn
  234.  
  235.     # Login, default anonymous
  236.     def login(self, user = '', passwd = '', acct = ''):
  237.         if not user: user = 'anonymous'
  238.         if user == 'anonymous' and passwd in ('', '-'):
  239.             thishost = socket.gethostname()
  240.             # Make sure it is fully qualified
  241.             if not '.' in thishost:
  242.                 thisaddr = socket.gethostbyname(thishost)
  243.                 firstname, names, unused = \
  244.                        socket.gethostbyaddr(thisaddr)
  245.                 names.insert(0, firstname)
  246.                 for name in names:
  247.                     if '.' in name:
  248.                         thishost = name
  249.                         break
  250.             try:
  251.                 if os.environ.has_key('LOGNAME'):
  252.                     realuser = os.environ['LOGNAME']
  253.                 elif os.environ.has_key('USER'):
  254.                     realuser = os.environ['USER']
  255.                 else:
  256.                     realuser = 'anonymous'
  257.             except AttributeError:
  258.                 # Not all systems have os.environ....
  259.                 realuser = 'anonymous'
  260.             passwd = passwd + realuser + '@' + thishost
  261.         resp = self.sendcmd('USER ' + user)
  262.         if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)
  263.         if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)
  264.         if resp[0] <> '2':
  265.             raise error_reply, resp
  266.  
  267.     # Retrieve data in binary mode.
  268.     # The argument is a RETR command.
  269.     # The callback function is called for each block.
  270.     # This creates a new port for you
  271.     def retrbinary(self, cmd, callback, blocksize):
  272.         self.voidcmd('TYPE I')
  273.         conn = self.transfercmd(cmd)
  274.         while 1:
  275.             data = conn.recv(blocksize)
  276.             if not data:
  277.                 break
  278.             callback(data)
  279.         conn.close()
  280.         self.voidresp()
  281.  
  282.     # Retrieve data in line mode.
  283.     # The argument is a RETR or LIST command.
  284.     # The callback function is called for each line, with trailing
  285.     # CRLF stripped.  This creates a new port for you.
  286.     # print_lines is the default callback 
  287.     def retrlines(self, cmd, callback = None):
  288.         if not callback: callback = print_line
  289.         resp = self.sendcmd('TYPE A')
  290.         conn = self.transfercmd(cmd)
  291.         fp = conn.makefile('r')
  292.         while 1:
  293.             line = fp.readline()
  294.             if self.debugging > 2: print '*retr*', `line`
  295.             if not line:
  296.                 break
  297.             if line[-2:] == CRLF:
  298.                 line = line[:-2]
  299.             elif line[:-1] == '\n':
  300.                 line = line[:-1]
  301.             callback(line)
  302.         fp.close()
  303.         conn.close()
  304.         self.voidresp()
  305.  
  306.     # Store a file in binary mode
  307.     def storbinary(self, cmd, fp, blocksize):
  308.         self.voidcmd('TYPE I')
  309.         conn = self.transfercmd(cmd)
  310.         while 1:
  311.             buf = fp.read(blocksize)
  312.             if not buf: break
  313.             conn.send(buf)
  314.         conn.close()
  315.         self.voidresp()
  316.  
  317.     # Store a file in line mode
  318.     def storlines(self, cmd, fp):
  319.         self.voidcmd('TYPE A')
  320.         conn = self.transfercmd(cmd)
  321.         while 1:
  322.             buf = fp.readline()
  323.             if not buf: break
  324.             if buf[-2:] <> CRLF:
  325.                 if buf[-1] in CRLF: buf = buf[:-1]
  326.                 buf = buf + CRLF
  327.             conn.send(buf)
  328.         conn.close()
  329.         self.voidresp()
  330.  
  331.     # Return a list of files in a given directory (default the current)
  332.     def nlst(self, *args):
  333.         cmd = 'NLST'
  334.         for arg in args:
  335.             cmd = cmd + (' ' + arg)
  336.         files = []
  337.         self.retrlines(cmd, files.append)
  338.         return files
  339.  
  340.     # List a directory in long form.  By default list current directory
  341.     # to stdout.  Optional last argument is callback function;
  342.     # all non-empty arguments before it are concatenated to the
  343.     # LIST command.  (This *should* only be used for a pathname.)
  344.     def dir(self, *args):
  345.         cmd = 'LIST' 
  346.         func = None
  347.         if args[-1:] and type(args[-1]) != type(''):
  348.             args, func = args[:-1], args[-1]
  349.         for arg in args:
  350.             if arg:
  351.                 cmd = cmd + (' ' + arg) 
  352.         self.retrlines(cmd, func)
  353.  
  354.     # Rename a file
  355.     def rename(self, fromname, toname):
  356.         resp = self.sendcmd('RNFR ' + fromname)
  357.         if resp[0] <> '3':
  358.             raise error_reply, resp
  359.         self.voidcmd('RNTO ' + toname)
  360.  
  361.         # Delete a file
  362.         def delete(self, filename):
  363.                 resp = self.sendcmd('DELE ' + filename)
  364.                 if resp[:3] == '250':
  365.                         return
  366.                 elif resp[:1] == '5':
  367.                         raise error_perm, resp
  368.                 else:
  369.                         raise error_reply, resp
  370.  
  371.     # Change to a directory
  372.     def cwd(self, dirname):
  373.         if dirname == '..':
  374.             try:
  375.                 self.voidcmd('CDUP')
  376.                 return
  377.             except error_perm, msg:
  378.                 if msg[:3] != '500':
  379.                     raise error_perm, msg
  380.         cmd = 'CWD ' + dirname
  381.         self.voidcmd(cmd)
  382.  
  383.     # Retrieve the size of a file
  384.     def size(self, filename):
  385.         resp = self.sendcmd('SIZE ' + filename)
  386.         if resp[:3] == '213':
  387.             return string.atoi(string.strip(resp[3:]))
  388.  
  389.     # Make a directory, return its full pathname
  390.     def mkd(self, dirname):
  391.         resp = self.sendcmd('MKD ' + dirname)
  392.         return parse257(resp)
  393.  
  394.     # Return current wording directory
  395.     def pwd(self):
  396.         resp = self.sendcmd('PWD')
  397.         return parse257(resp)
  398.  
  399.     # Quit, and close the connection
  400.     def quit(self):
  401.         self.voidcmd('QUIT')
  402.         self.close()
  403.  
  404.     # Close the connection without assuming anything about it
  405.     def close(self):
  406.         self.file.close()
  407.         self.sock.close()
  408.         del self.file, self.sock
  409.  
  410.  
  411. # Parse a response type 257
  412. def parse257(resp):
  413.     if resp[:3] <> '257':
  414.         raise error_reply, resp
  415.     if resp[3:5] <> ' "':
  416.         return '' # Not compliant to RFC 959, but UNIX ftpd does this
  417.     dirname = ''
  418.     i = 5
  419.     n = len(resp)
  420.     while i < n:
  421.         c = resp[i]
  422.         i = i+1
  423.         if c == '"':
  424.             if i >= n or resp[i] <> '"':
  425.                 break
  426.             i = i+1
  427.         dirname = dirname + c
  428.     return dirname
  429.  
  430. # Default retrlines callback to print a line
  431. def print_line(line):
  432.     print line
  433.  
  434.  
  435. # Test program.
  436. # Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
  437. def test():
  438.     import marshal
  439.     debugging = 0
  440.     while sys.argv[1] == '-d':
  441.         debugging = debugging+1
  442.         del sys.argv[1]
  443.     host = sys.argv[1]
  444.     ftp = FTP(host)
  445.     ftp.set_debuglevel(debugging)
  446.     ftp.login()
  447.     for file in sys.argv[2:]:
  448.         if file[:2] == '-l':
  449.             ftp.dir(file[2:])
  450.         elif file[:2] == '-d':
  451.             cmd = 'CWD'
  452.             if file[2:]: cmd = cmd + ' ' + file[2:]
  453.             resp = ftp.sendcmd(cmd)
  454.         else:
  455.             ftp.retrbinary('RETR ' + file, \
  456.                        sys.stdout.write, 1024)
  457.     ftp.quit()
  458.  
  459.  
  460. if __name__ == '__main__':
  461.     test()
  462.