home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Lib / ftplib.py < prev    next >
Text File  |  1994-02-18  |  12KB  |  450 lines

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