home *** CD-ROM | disk | FTP | other *** search
/ Mundo do CD-ROM 118 / cdrom118.iso / internet / webaroo / WebarooSetup.exe / Webaroo.msi / _A0DEB44B94924E89917E71AA90C5F226 / ftplib.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2005-12-23  |  25.7 KB  |  969 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. """An FTP client class and some helper functions.
  5.  
  6. Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
  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 anonymous@
  13. '230 Guest login ok, access restrictions apply.'
  14. >>> ftp.retrlines('LIST') # list directory contents
  15. total 9
  16. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
  17. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
  18. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
  19. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
  20. d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
  21. drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
  22. drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
  23. drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
  24. -rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
  25. '226 Transfer complete.'
  26. >>> ftp.quit()
  27. '221 Goodbye.'
  28. >>>
  29.  
  30. A nice test that reveals some of the network dialogue would be:
  31. python ftplib.py -d localhost -l -p -l
  32. """
  33. import os
  34. import sys
  35.  
  36. try:
  37.     import SOCKS
  38.     socket = SOCKS
  39.     del SOCKS
  40.     from socket import getfqdn
  41.     socket.getfqdn = getfqdn
  42.     del getfqdn
  43. except ImportError:
  44.     import socket
  45.  
  46. __all__ = [
  47.     'FTP',
  48.     'Netrc']
  49. MSG_OOB = 1
  50. FTP_PORT = 21
  51.  
  52. class Error(Exception):
  53.     pass
  54.  
  55.  
  56. class error_reply(Error):
  57.     pass
  58.  
  59.  
  60. class error_temp(Error):
  61.     pass
  62.  
  63.  
  64. class error_perm(Error):
  65.     pass
  66.  
  67.  
  68. class error_proto(Error):
  69.     pass
  70.  
  71. all_errors = (Error, socket.error, IOError, EOFError)
  72. CRLF = '\r\n'
  73.  
  74. class FTP:
  75.     """An FTP client class.
  76.  
  77.     To create a connection, call the class using these argument:
  78.             host, user, passwd, acct
  79.     These are all strings, and have default value ''.
  80.     Then use self.connect() with optional host and port argument.
  81.  
  82.     To download a file, use ftp.retrlines('RETR ' + filename),
  83.     or ftp.retrbinary() with slightly different arguments.
  84.     To upload a file, use ftp.storlines() or ftp.storbinary(),
  85.     which have an open file as argument (see their definitions
  86.     below for details).
  87.     The download/upload functions first issue appropriate TYPE
  88.     and PORT or PASV commands.
  89. """
  90.     debugging = 0
  91.     host = ''
  92.     port = FTP_PORT
  93.     sock = None
  94.     file = None
  95.     welcome = None
  96.     passiveserver = 1
  97.     
  98.     def __init__(self, host = '', user = '', passwd = '', acct = ''):
  99.         if host:
  100.             self.connect(host)
  101.             if user:
  102.                 self.login(user, passwd, acct)
  103.             
  104.         
  105.  
  106.     
  107.     def connect(self, host = '', port = 0):
  108.         '''Connect to host.  Arguments are:
  109.         - host: hostname to connect to (string, default previous host)
  110.         - port: port to connect to (integer, default previous port)'''
  111.         if host:
  112.             self.host = host
  113.         
  114.         if port:
  115.             self.port = port
  116.         
  117.         msg = 'getaddrinfo returns an empty list'
  118.         for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
  119.             (af, socktype, proto, canonname, sa) = res
  120.             
  121.             try:
  122.                 self.sock = socket.socket(af, socktype, proto)
  123.                 self.sock.connect(sa)
  124.             except socket.error:
  125.                 msg = None
  126.                 if self.sock:
  127.                     self.sock.close()
  128.                 
  129.                 self.sock = None
  130.                 continue
  131.  
  132.         
  133.         if not self.sock:
  134.             raise socket.error, msg
  135.         
  136.         self.af = af
  137.         self.file = self.sock.makefile('rb')
  138.         self.welcome = self.getresp()
  139.         return self.welcome
  140.  
  141.     
  142.     def getwelcome(self):
  143.         '''Get the welcome message from the server.
  144.         (this is read and squirreled away by connect())'''
  145.         if self.debugging:
  146.             print '*welcome*', self.sanitize(self.welcome)
  147.         
  148.         return self.welcome
  149.  
  150.     
  151.     def set_debuglevel(self, level):
  152.         '''Set the debugging level.
  153.         The required argument level means:
  154.         0: no debugging output (default)
  155.         1: print commands and responses but not body text etc.
  156.         2: also print raw lines read and sent before stripping CR/LF'''
  157.         self.debugging = level
  158.  
  159.     debug = set_debuglevel
  160.     
  161.     def set_pasv(self, val):
  162.         '''Use passive or active mode for data transfers.
  163.         With a false argument, use the normal PORT mode,
  164.         With a true argument, use the PASV command.'''
  165.         self.passiveserver = val
  166.  
  167.     
  168.     def sanitize(self, s):
  169.         if s[:5] == 'pass ' or s[:5] == 'PASS ':
  170.             i = len(s)
  171.             while i > 5 and s[i - 1] in '\r\n':
  172.                 i = i - 1
  173.             s = s[:5] + '*' * (i - 5) + s[i:]
  174.         
  175.         return repr(s)
  176.  
  177.     
  178.     def putline(self, line):
  179.         line = line + CRLF
  180.         if self.debugging > 1:
  181.             print '*put*', self.sanitize(line)
  182.         
  183.         self.sock.sendall(line)
  184.  
  185.     
  186.     def putcmd(self, line):
  187.         if self.debugging:
  188.             print '*cmd*', self.sanitize(line)
  189.         
  190.         self.putline(line)
  191.  
  192.     
  193.     def getline(self):
  194.         line = self.file.readline()
  195.         if self.debugging > 1:
  196.             print '*get*', self.sanitize(line)
  197.         
  198.         if not line:
  199.             raise EOFError
  200.         
  201.         if line[-2:] == CRLF:
  202.             line = line[:-2]
  203.         elif line[-1:] in CRLF:
  204.             line = line[:-1]
  205.         
  206.         return line
  207.  
  208.     
  209.     def getmultiline(self):
  210.         line = self.getline()
  211.         if line[3:4] == '-':
  212.             code = line[:3]
  213.             while None:
  214.                 nextline = self.getline()
  215.                 line = line + '\n' + nextline
  216.                 if nextline[:3] == code and nextline[3:4] != '-':
  217.                     break
  218.                     continue
  219.         
  220.         return line
  221.  
  222.     
  223.     def getresp(self):
  224.         resp = self.getmultiline()
  225.         if self.debugging:
  226.             print '*resp*', self.sanitize(resp)
  227.         
  228.         self.lastresp = resp[:3]
  229.         c = resp[:1]
  230.         if c == '4':
  231.             raise error_temp, resp
  232.         
  233.         if c == '5':
  234.             raise error_perm, resp
  235.         
  236.         if c not in '123':
  237.             raise error_proto, resp
  238.         
  239.         return resp
  240.  
  241.     
  242.     def voidresp(self):
  243.         """Expect a response beginning with '2'."""
  244.         resp = self.getresp()
  245.         if resp[0] != '2':
  246.             raise error_reply, resp
  247.         
  248.         return resp
  249.  
  250.     
  251.     def abort(self):
  252.         """Abort a file transfer.  Uses out-of-band data.
  253.         This does not follow the procedure from the RFC to send Telnet
  254.         IP and Synch; that doesn't seem to work with the servers I've
  255.         tried.  Instead, just send the ABOR command as OOB data."""
  256.         line = 'ABOR' + CRLF
  257.         if self.debugging > 1:
  258.             print '*put urgent*', self.sanitize(line)
  259.         
  260.         self.sock.sendall(line, MSG_OOB)
  261.         resp = self.getmultiline()
  262.         if resp[:3] not in ('426', '226'):
  263.             raise error_proto, resp
  264.         
  265.  
  266.     
  267.     def sendcmd(self, cmd):
  268.         '''Send a command and return the response.'''
  269.         self.putcmd(cmd)
  270.         return self.getresp()
  271.  
  272.     
  273.     def voidcmd(self, cmd):
  274.         """Send a command and expect a response beginning with '2'."""
  275.         self.putcmd(cmd)
  276.         return self.voidresp()
  277.  
  278.     
  279.     def sendport(self, host, port):
  280.         '''Send a PORT command with the current host and the given
  281.         port number.
  282.         '''
  283.         hbytes = host.split('.')
  284.         pbytes = [
  285.             repr(port / 256),
  286.             repr(port % 256)]
  287.         bytes = hbytes + pbytes
  288.         cmd = 'PORT ' + ','.join(bytes)
  289.         return self.voidcmd(cmd)
  290.  
  291.     
  292.     def sendeprt(self, host, port):
  293.         '''Send a EPRT command with the current host and the given port number.'''
  294.         af = 0
  295.         if self.af == socket.AF_INET:
  296.             af = 1
  297.         
  298.         if self.af == socket.AF_INET6:
  299.             af = 2
  300.         
  301.         if af == 0:
  302.             raise error_proto, 'unsupported address family'
  303.         
  304.         fields = [
  305.             '',
  306.             repr(af),
  307.             host,
  308.             repr(port),
  309.             '']
  310.         cmd = 'EPRT ' + '|'.join(fields)
  311.         return self.voidcmd(cmd)
  312.  
  313.     
  314.     def makeport(self):
  315.         '''Create a new socket and send a PORT command for it.'''
  316.         msg = 'getaddrinfo returns an empty list'
  317.         sock = None
  318.         for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
  319.             (af, socktype, proto, canonname, sa) = res
  320.             
  321.             try:
  322.                 sock = socket.socket(af, socktype, proto)
  323.                 sock.bind(sa)
  324.             except socket.error:
  325.                 msg = None
  326.                 if sock:
  327.                     sock.close()
  328.                 
  329.                 sock = None
  330.                 continue
  331.  
  332.         
  333.         if not sock:
  334.             raise socket.error, msg
  335.         
  336.         sock.listen(1)
  337.         port = sock.getsockname()[1]
  338.         host = self.sock.getsockname()[0]
  339.         if self.af == socket.AF_INET:
  340.             resp = self.sendport(host, port)
  341.         else:
  342.             resp = self.sendeprt(host, port)
  343.         return sock
  344.  
  345.     
  346.     def makepasv(self):
  347.         if self.af == socket.AF_INET:
  348.             (host, port) = parse227(self.sendcmd('PASV'))
  349.         else:
  350.             (host, port) = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
  351.         return (host, port)
  352.  
  353.     
  354.     def ntransfercmd(self, cmd, rest = None):
  355.         """Initiate a transfer over the data connection.
  356.  
  357.         If the transfer is active, send a port command and the
  358.         transfer command, and accept the connection.  If the server is
  359.         passive, send a pasv command, connect to it, and start the
  360.         transfer command.  Either way, return the socket for the
  361.         connection and the expected size of the transfer.  The
  362.         expected size may be None if it could not be determined.
  363.  
  364.         Optional `rest' argument can be a string that is sent as the
  365.         argument to a RESTART command.  This is essentially a server
  366.         marker used to tell the server to skip over any data up to the
  367.         given marker.
  368.         """
  369.         size = None
  370.         if self.passiveserver:
  371.             (host, port) = self.makepasv()
  372.             (af, socktype, proto, canon, sa) = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0]
  373.             conn = socket.socket(af, socktype, proto)
  374.             conn.connect(sa)
  375.             if rest is not None:
  376.                 self.sendcmd('REST %s' % rest)
  377.             
  378.             resp = self.sendcmd(cmd)
  379.             if resp[0] != '1':
  380.                 raise error_reply, resp
  381.             
  382.         else:
  383.             sock = self.makeport()
  384.             if rest is not None:
  385.                 self.sendcmd('REST %s' % rest)
  386.             
  387.             resp = self.sendcmd(cmd)
  388.             if resp[0] != '1':
  389.                 raise error_reply, resp
  390.             
  391.             (conn, sockaddr) = sock.accept()
  392.         if resp[:3] == '150':
  393.             size = parse150(resp)
  394.         
  395.         return (conn, size)
  396.  
  397.     
  398.     def transfercmd(self, cmd, rest = None):
  399.         '''Like ntransfercmd() but returns only the socket.'''
  400.         return self.ntransfercmd(cmd, rest)[0]
  401.  
  402.     
  403.     def login(self, user = '', passwd = '', acct = ''):
  404.         '''Login, default anonymous.'''
  405.         if not user:
  406.             user = 'anonymous'
  407.         
  408.         if not passwd:
  409.             passwd = ''
  410.         
  411.         if not acct:
  412.             acct = ''
  413.         
  414.         if user == 'anonymous' and passwd in ('', '-'):
  415.             passwd = passwd + 'anonymous@'
  416.         
  417.         resp = self.sendcmd('USER ' + user)
  418.         if resp[0] == '3':
  419.             resp = self.sendcmd('PASS ' + passwd)
  420.         
  421.         if resp[0] == '3':
  422.             resp = self.sendcmd('ACCT ' + acct)
  423.         
  424.         if resp[0] != '2':
  425.             raise error_reply, resp
  426.         
  427.         return resp
  428.  
  429.     
  430.     def retrbinary(self, cmd, callback, blocksize = 8192, rest = None):
  431.         """Retrieve data in binary mode.
  432.  
  433.         `cmd' is a RETR command.  `callback' is a callback function is
  434.         called for each block.  No more than `blocksize' number of
  435.         bytes will be read from the socket.  Optional `rest' is passed
  436.         to transfercmd().
  437.  
  438.         A new port is created for you.  Return the response code.
  439.         """
  440.         self.voidcmd('TYPE I')
  441.         conn = self.transfercmd(cmd, rest)
  442.         while None:
  443.             data = conn.recv(blocksize)
  444.             if not data:
  445.                 break
  446.             
  447.         conn.close()
  448.         return self.voidresp()
  449.  
  450.     
  451.     def retrlines(self, cmd, callback = None):
  452.         '''Retrieve data in line mode.
  453.         The argument is a RETR or LIST command.
  454.         The callback function (2nd argument) is called for each line,
  455.         with trailing CRLF stripped.  This creates a new port for you.
  456.         print_line() is the default callback.'''
  457.         if callback is None:
  458.             callback = print_line
  459.         
  460.         resp = self.sendcmd('TYPE A')
  461.         conn = self.transfercmd(cmd)
  462.         fp = conn.makefile('rb')
  463.         while None:
  464.             line = fp.readline()
  465.             if self.debugging > 2:
  466.                 print '*retr*', repr(line)
  467.             
  468.             if not line:
  469.                 break
  470.             
  471.             if line[-2:] == CRLF:
  472.                 line = line[:-2]
  473.             elif line[-1:] == '\n':
  474.                 line = line[:-1]
  475.             
  476.         fp.close()
  477.         conn.close()
  478.         return self.voidresp()
  479.  
  480.     
  481.     def storbinary(self, cmd, fp, blocksize = 8192):
  482.         '''Store a file in binary mode.'''
  483.         self.voidcmd('TYPE I')
  484.         conn = self.transfercmd(cmd)
  485.         while None:
  486.             buf = fp.read(blocksize)
  487.             if not buf:
  488.                 break
  489.             
  490.         conn.close()
  491.         return self.voidresp()
  492.  
  493.     
  494.     def storlines(self, cmd, fp):
  495.         '''Store a file in line mode.'''
  496.         self.voidcmd('TYPE A')
  497.         conn = self.transfercmd(cmd)
  498.         while None:
  499.             buf = fp.readline()
  500.             if not buf:
  501.                 break
  502.             
  503.             if buf[-2:] != CRLF:
  504.                 if buf[-1] in CRLF:
  505.                     buf = buf[:-1]
  506.                 
  507.                 buf = buf + CRLF
  508.             
  509.         conn.close()
  510.         return self.voidresp()
  511.  
  512.     
  513.     def acct(self, password):
  514.         '''Send new account name.'''
  515.         cmd = 'ACCT ' + password
  516.         return self.voidcmd(cmd)
  517.  
  518.     
  519.     def nlst(self, *args):
  520.         '''Return a list of files in a given directory (default the current).'''
  521.         cmd = 'NLST'
  522.         for arg in args:
  523.             cmd = cmd + ' ' + arg
  524.         
  525.         files = []
  526.         self.retrlines(cmd, files.append)
  527.         return files
  528.  
  529.     
  530.     def dir(self, *args):
  531.         '''List a directory in long form.
  532.         By default list current directory to stdout.
  533.         Optional last argument is callback function; all
  534.         non-empty arguments before it are concatenated to the
  535.         LIST command.  (This *should* only be used for a pathname.)'''
  536.         cmd = 'LIST'
  537.         func = None
  538.         if args[-1:] and type(args[-1]) != type(''):
  539.             args = args[:-1]
  540.             func = args[-1]
  541.         
  542.         for arg in args:
  543.             if arg:
  544.                 cmd = cmd + ' ' + arg
  545.                 continue
  546.         
  547.         self.retrlines(cmd, func)
  548.  
  549.     
  550.     def rename(self, fromname, toname):
  551.         '''Rename a file.'''
  552.         resp = self.sendcmd('RNFR ' + fromname)
  553.         if resp[0] != '3':
  554.             raise error_reply, resp
  555.         
  556.         return self.voidcmd('RNTO ' + toname)
  557.  
  558.     
  559.     def delete(self, filename):
  560.         '''Delete a file.'''
  561.         resp = self.sendcmd('DELE ' + filename)
  562.         if resp[:3] in ('250', '200'):
  563.             return resp
  564.         elif resp[:1] == '5':
  565.             raise error_perm, resp
  566.         else:
  567.             raise error_reply, resp
  568.  
  569.     
  570.     def cwd(self, dirname):
  571.         '''Change to a directory.'''
  572.         if dirname == '..':
  573.             
  574.             try:
  575.                 return self.voidcmd('CDUP')
  576.             except error_perm:
  577.                 msg = None
  578.                 if msg.args[0][:3] != '500':
  579.                     raise 
  580.                 
  581.             except:
  582.                 msg.args[0][:3] != '500'
  583.             
  584.  
  585.         None<EXCEPTION MATCH>error_perm
  586.         if dirname == '':
  587.             dirname = '.'
  588.         
  589.         cmd = 'CWD ' + dirname
  590.         return self.voidcmd(cmd)
  591.  
  592.     
  593.     def size(self, filename):
  594.         '''Retrieve the size of a file.'''
  595.         resp = self.sendcmd('SIZE ' + filename)
  596.         if resp[:3] == '213':
  597.             s = resp[3:].strip()
  598.             
  599.             try:
  600.                 return int(s)
  601.             except (OverflowError, ValueError):
  602.                 return long(s)
  603.             except:
  604.                 None<EXCEPTION MATCH>(OverflowError, ValueError)
  605.             
  606.  
  607.         None<EXCEPTION MATCH>(OverflowError, ValueError)
  608.  
  609.     
  610.     def mkd(self, dirname):
  611.         '''Make a directory, return its full pathname.'''
  612.         resp = self.sendcmd('MKD ' + dirname)
  613.         return parse257(resp)
  614.  
  615.     
  616.     def rmd(self, dirname):
  617.         '''Remove a directory.'''
  618.         return self.voidcmd('RMD ' + dirname)
  619.  
  620.     
  621.     def pwd(self):
  622.         '''Return current working directory.'''
  623.         resp = self.sendcmd('PWD')
  624.         return parse257(resp)
  625.  
  626.     
  627.     def quit(self):
  628.         '''Quit, and close the connection.'''
  629.         resp = self.voidcmd('QUIT')
  630.         self.close()
  631.         return resp
  632.  
  633.     
  634.     def close(self):
  635.         '''Close the connection without assuming anything about it.'''
  636.         if self.file:
  637.             self.file.close()
  638.             self.sock.close()
  639.             self.file = None
  640.             self.sock = None
  641.         
  642.  
  643.  
  644. _150_re = None
  645.  
  646. def parse150(resp):
  647.     """Parse the '150' response for a RETR request.
  648.     Returns the expected transfer size or None; size is not guaranteed to
  649.     be present in the 150 message.
  650.     """
  651.     global _150_re
  652.     if resp[:3] != '150':
  653.         raise error_reply, resp
  654.     
  655.     if _150_re is None:
  656.         import re
  657.         _150_re = re.compile('150 .* \\((\\d+) bytes\\)', re.IGNORECASE)
  658.     
  659.     m = _150_re.match(resp)
  660.     if not m:
  661.         return None
  662.     
  663.     s = m.group(1)
  664.     
  665.     try:
  666.         return int(s)
  667.     except (OverflowError, ValueError):
  668.         return long(s)
  669.  
  670.  
  671. _227_re = None
  672.  
  673. def parse227(resp):
  674.     """Parse the '227' response for a PASV request.
  675.     Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
  676.     Return ('host.addr.as.numbers', port#) tuple."""
  677.     global _227_re
  678.     if resp[:3] != '227':
  679.         raise error_reply, resp
  680.     
  681.     if _227_re is None:
  682.         import re
  683.         _227_re = re.compile('(\\d+),(\\d+),(\\d+),(\\d+),(\\d+),(\\d+)')
  684.     
  685.     m = _227_re.search(resp)
  686.     if not m:
  687.         raise error_proto, resp
  688.     
  689.     numbers = m.groups()
  690.     host = '.'.join(numbers[:4])
  691.     port = (int(numbers[4]) << 8) + int(numbers[5])
  692.     return (host, port)
  693.  
  694.  
  695. def parse229(resp, peer):
  696.     """Parse the '229' response for a EPSV request.
  697.     Raises error_proto if it does not contain '(|||port|)'
  698.     Return ('host.addr.as.numbers', port#) tuple."""
  699.     if resp[:3] != '229':
  700.         raise error_reply, resp
  701.     
  702.     left = resp.find('(')
  703.     if left < 0:
  704.         raise error_proto, resp
  705.     
  706.     right = resp.find(')', left + 1)
  707.     if right < 0:
  708.         raise error_proto, resp
  709.     
  710.     if resp[left + 1] != resp[right - 1]:
  711.         raise error_proto, resp
  712.     
  713.     parts = resp[left + 1:right].split(resp[left + 1])
  714.     if len(parts) != 5:
  715.         raise error_proto, resp
  716.     
  717.     host = peer[0]
  718.     port = int(parts[3])
  719.     return (host, port)
  720.  
  721.  
  722. def parse257(resp):
  723.     """Parse the '257' response for a MKD or PWD request.
  724.     This is a response to a MKD or PWD request: a directory name.
  725.     Returns the directoryname in the 257 reply."""
  726.     if resp[:3] != '257':
  727.         raise error_reply, resp
  728.     
  729.     if resp[3:5] != ' "':
  730.         return ''
  731.     
  732.     dirname = ''
  733.     i = 5
  734.     n = len(resp)
  735.     while i < n:
  736.         c = resp[i]
  737.         i = i + 1
  738.         if c == '"':
  739.             if i >= n or resp[i] != '"':
  740.                 break
  741.             
  742.             i = i + 1
  743.         
  744.         dirname = dirname + c
  745.     return dirname
  746.  
  747.  
  748. def print_line(line):
  749.     '''Default retrlines callback to print a line.'''
  750.     print line
  751.  
  752.  
  753. def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
  754.     '''Copy file from one FTP-instance to another.'''
  755.     if not targetname:
  756.         targetname = sourcename
  757.     
  758.     type = 'TYPE ' + type
  759.     source.voidcmd(type)
  760.     target.voidcmd(type)
  761.     (sourcehost, sourceport) = parse227(source.sendcmd('PASV'))
  762.     target.sendport(sourcehost, sourceport)
  763.     treply = target.sendcmd('STOR ' + targetname)
  764.     if treply[:3] not in ('125', '150'):
  765.         raise error_proto
  766.     
  767.     sreply = source.sendcmd('RETR ' + sourcename)
  768.     if sreply[:3] not in ('125', '150'):
  769.         raise error_proto
  770.     
  771.     source.voidresp()
  772.     target.voidresp()
  773.  
  774.  
  775. class Netrc:
  776.     """Class to parse & provide access to 'netrc' format files.
  777.  
  778.     See the netrc(4) man page for information on the file format.
  779.  
  780.     WARNING: This class is obsolete -- use module netrc instead.
  781.  
  782.     """
  783.     __defuser = None
  784.     __defpasswd = None
  785.     __defacct = None
  786.     
  787.     def __init__(self, filename = None):
  788.         if filename is None:
  789.             if 'HOME' in os.environ:
  790.                 filename = os.path.join(os.environ['HOME'], '.netrc')
  791.             else:
  792.                 raise IOError, 'specify file to load or set $HOME'
  793.         
  794.         self._Netrc__hosts = { }
  795.         self._Netrc__macros = { }
  796.         fp = open(filename, 'r')
  797.         in_macro = 0
  798.         while None:
  799.             line = fp.readline()
  800.             if not line:
  801.                 break
  802.             
  803.             if in_macro and line.strip():
  804.                 macro_lines.append(line)
  805.                 continue
  806.             elif in_macro:
  807.                 self._Netrc__macros[macro_name] = tuple(macro_lines)
  808.                 in_macro = 0
  809.             
  810.             words = line.split()
  811.             host = None
  812.             user = None
  813.             passwd = None
  814.             acct = None
  815.             default = 0
  816.             i = 0
  817.             while i < len(words):
  818.                 w1 = words[i]
  819.                 if i + 1 < len(words):
  820.                     w2 = words[i + 1]
  821.                 else:
  822.                     w2 = None
  823.                 if w1 == 'default':
  824.                     default = 1
  825.                 elif w1 == 'machine' and w2:
  826.                     host = w2.lower()
  827.                     i = i + 1
  828.                 elif w1 == 'login' and w2:
  829.                     user = w2
  830.                     i = i + 1
  831.                 elif w1 == 'password' and w2:
  832.                     passwd = w2
  833.                     i = i + 1
  834.                 elif w1 == 'account' and w2:
  835.                     acct = w2
  836.                     i = i + 1
  837.                 elif w1 == 'macdef' and w2:
  838.                     macro_name = w2
  839.                     macro_lines = []
  840.                     in_macro = 1
  841.                     break
  842.                 
  843.                 i = i + 1
  844.             if default:
  845.                 if not user:
  846.                     pass
  847.                 self._Netrc__defuser = self._Netrc__defuser
  848.                 if not passwd:
  849.                     pass
  850.                 self._Netrc__defpasswd = self._Netrc__defpasswd
  851.                 if not acct:
  852.                     pass
  853.                 self._Netrc__defacct = self._Netrc__defacct
  854.             
  855.             if host:
  856.                 if host in self._Netrc__hosts:
  857.                     (ouser, opasswd, oacct) = self._Netrc__hosts[host]
  858.                     if not user:
  859.                         pass
  860.                     user = ouser
  861.                     if not passwd:
  862.                         pass
  863.                     passwd = opasswd
  864.                     if not acct:
  865.                         pass
  866.                     acct = oacct
  867.                 
  868.                 self._Netrc__hosts[host] = (user, passwd, acct)
  869.                 continue
  870.         fp.close()
  871.  
  872.     
  873.     def get_hosts(self):
  874.         '''Return a list of hosts mentioned in the .netrc file.'''
  875.         return self._Netrc__hosts.keys()
  876.  
  877.     
  878.     def get_account(self, host):
  879.         '''Returns login information for the named host.
  880.  
  881.         The return value is a triple containing userid,
  882.         password, and the accounting field.
  883.  
  884.         '''
  885.         host = host.lower()
  886.         user = None
  887.         passwd = None
  888.         acct = None
  889.         if host in self._Netrc__hosts:
  890.             (user, passwd, acct) = self._Netrc__hosts[host]
  891.         
  892.         if not user:
  893.             pass
  894.         user = self._Netrc__defuser
  895.         if not passwd:
  896.             pass
  897.         passwd = self._Netrc__defpasswd
  898.         if not acct:
  899.             pass
  900.         acct = self._Netrc__defacct
  901.         return (user, passwd, acct)
  902.  
  903.     
  904.     def get_macros(self):
  905.         '''Return a list of all defined macro names.'''
  906.         return self._Netrc__macros.keys()
  907.  
  908.     
  909.     def get_macro(self, macro):
  910.         '''Return a sequence of lines which define a named macro.'''
  911.         return self._Netrc__macros[macro]
  912.  
  913.  
  914.  
  915. def test():
  916.     '''Test program.
  917.     Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...'''
  918.     debugging = 0
  919.     rcfile = None
  920.     while sys.argv[1] == '-d':
  921.         debugging = debugging + 1
  922.         del sys.argv[1]
  923.     if sys.argv[1][:2] == '-r':
  924.         rcfile = sys.argv[1][2:]
  925.         del sys.argv[1]
  926.     
  927.     host = sys.argv[1]
  928.     ftp = FTP(host)
  929.     ftp.set_debuglevel(debugging)
  930.     userid = passwd = acct = ''
  931.     
  932.     try:
  933.         netrc = Netrc(rcfile)
  934.     except IOError:
  935.         if rcfile is not None:
  936.             sys.stderr.write('Could not open account file -- using anonymous login.')
  937.         
  938.     except:
  939.         rcfile is not None
  940.  
  941.     
  942.     try:
  943.         (userid, passwd, acct) = netrc.get_account(host)
  944.     except KeyError:
  945.         sys.stderr.write('No account -- using anonymous login.')
  946.  
  947.     ftp.login(userid, passwd, acct)
  948.     for file in sys.argv[2:]:
  949.         if file[:2] == '-l':
  950.             ftp.dir(file[2:])
  951.             continue
  952.         if file[:2] == '-d':
  953.             cmd = 'CWD'
  954.             if file[2:]:
  955.                 cmd = cmd + ' ' + file[2:]
  956.             
  957.             resp = ftp.sendcmd(cmd)
  958.             continue
  959.         if file == '-p':
  960.             ftp.set_pasv(not (ftp.passiveserver))
  961.             continue
  962.         ftp.retrbinary('RETR ' + file, sys.stdout.write, 1024)
  963.     
  964.     ftp.quit()
  965.  
  966. if __name__ == '__main__':
  967.     test()
  968.  
  969.