-"""An FTP client class and some helper functions.\r
-\r
-Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds\r
-\r
-Example:\r
-\r
->>> from ftplib import FTP\r
->>> ftp = FTP('ftp.python.org') # connect to host, default port\r
->>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@\r
-'230 Guest login ok, access restrictions apply.'\r
->>> ftp.retrlines('LIST') # list directory contents\r
-total 9\r
-drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .\r
-drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..\r
-drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin\r
-drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc\r
-d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming\r
-drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib\r
-drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub\r
-drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr\r
--rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg\r
-'226 Transfer complete.'\r
->>> ftp.quit()\r
-'221 Goodbye.'\r
->>>\r
-\r
-A nice test that reveals some of the network dialogue would be:\r
-python ftplib.py -d localhost -l -p -l\r
-"""\r
-\r
-#\r
-# Changes and improvements suggested by Steve Majewski.\r
-# Modified by Jack to work on the mac.\r
-# Modified by Siebren to support docstrings and PASV.\r
-# Modified by Phil Schwartz to add storbinary and storlines callbacks.\r
-# Modified by Giampaolo Rodola' to add TLS support.\r
-#\r
-\r
-import os\r
-import sys\r
-\r
-# Import SOCKS module if it exists, else standard socket module socket\r
-try:\r
- import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket\r
- from socket import getfqdn; socket.getfqdn = getfqdn; del getfqdn\r
-except ImportError:\r
- import socket\r
-from socket import _GLOBAL_DEFAULT_TIMEOUT\r
-\r
-__all__ = ["FTP","Netrc"]\r
-\r
-# Magic number from <socket.h>\r
-MSG_OOB = 0x1 # Process data out of band\r
-\r
-\r
-# The standard FTP server control port\r
-FTP_PORT = 21\r
-\r
-\r
-# Exception raised when an error or invalid response is received\r
-class Error(Exception): pass\r
-class error_reply(Error): pass # unexpected [123]xx reply\r
-class error_temp(Error): pass # 4xx errors\r
-class error_perm(Error): pass # 5xx errors\r
-class error_proto(Error): pass # response does not begin with [1-5]\r
-\r
-\r
-# All exceptions (hopefully) that may be raised here and that aren't\r
-# (always) programming errors on our side\r
-all_errors = (Error, IOError, EOFError)\r
-\r
-\r
-# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)\r
-CRLF = '\r\n'\r
-\r
-# The class itself\r
-class FTP:\r
-\r
- '''An FTP client class.\r
-\r
- To create a connection, call the class using these arguments:\r
- host, user, passwd, acct, timeout\r
-\r
- The first four arguments are all strings, and have default value ''.\r
- timeout must be numeric and defaults to None if not passed,\r
- meaning that no timeout will be set on any ftp socket(s)\r
- If a timeout is passed, then this is now the default timeout for all ftp\r
- socket operations for this instance.\r
-\r
- Then use self.connect() with optional host and port argument.\r
-\r
- To download a file, use ftp.retrlines('RETR ' + filename),\r
- or ftp.retrbinary() with slightly different arguments.\r
- To upload a file, use ftp.storlines() or ftp.storbinary(),\r
- which have an open file as argument (see their definitions\r
- below for details).\r
- The download/upload functions first issue appropriate TYPE\r
- and PORT or PASV commands.\r
-'''\r
-\r
- debugging = 0\r
- host = ''\r
- port = FTP_PORT\r
- sock = None\r
- file = None\r
- welcome = None\r
- passiveserver = 1\r
-\r
- # Initialization method (called by class instantiation).\r
- # Initialize host to localhost, port to standard ftp port\r
- # Optional arguments are host (for connect()),\r
- # and user, passwd, acct (for login())\r
- def __init__(self, host='', user='', passwd='', acct='',\r
- timeout=_GLOBAL_DEFAULT_TIMEOUT):\r
- self.timeout = timeout\r
- if host:\r
- self.connect(host)\r
- if user:\r
- self.login(user, passwd, acct)\r
-\r
- def connect(self, host='', port=0, timeout=-999):\r
- '''Connect to host. Arguments are:\r
- - host: hostname to connect to (string, default previous host)\r
- - port: port to connect to (integer, default previous port)\r
- '''\r
- if host != '':\r
- self.host = host\r
- if port > 0:\r
- self.port = port\r
- if timeout != -999:\r
- self.timeout = timeout\r
- self.sock = socket.create_connection((self.host, self.port), self.timeout)\r
- self.af = self.sock.family\r
- self.file = self.sock.makefile('rb')\r
- self.welcome = self.getresp()\r
- return self.welcome\r
-\r
- def getwelcome(self):\r
- '''Get the welcome message from the server.\r
- (this is read and squirreled away by connect())'''\r
- if self.debugging:\r
- print '*welcome*', self.sanitize(self.welcome)\r
- return self.welcome\r
-\r
- def set_debuglevel(self, level):\r
- '''Set the debugging level.\r
- The required argument level means:\r
- 0: no debugging output (default)\r
- 1: print commands and responses but not body text etc.\r
- 2: also print raw lines read and sent before stripping CR/LF'''\r
- self.debugging = level\r
- debug = set_debuglevel\r
-\r
- def set_pasv(self, val):\r
- '''Use passive or active mode for data transfers.\r
- With a false argument, use the normal PORT mode,\r
- With a true argument, use the PASV command.'''\r
- self.passiveserver = val\r
-\r
- # Internal: "sanitize" a string for printing\r
- def sanitize(self, s):\r
- if s[:5] == 'pass ' or s[:5] == 'PASS ':\r
- i = len(s)\r
- while i > 5 and s[i-1] in '\r\n':\r
- i = i-1\r
- s = s[:5] + '*'*(i-5) + s[i:]\r
- return repr(s)\r
-\r
- # Internal: send one line to the server, appending CRLF\r
- def putline(self, line):\r
- line = line + CRLF\r
- if self.debugging > 1: print '*put*', self.sanitize(line)\r
- self.sock.sendall(line)\r
-\r
- # Internal: send one command to the server (through putline())\r
- def putcmd(self, line):\r
- if self.debugging: print '*cmd*', self.sanitize(line)\r
- self.putline(line)\r
-\r
- # Internal: return one line from the server, stripping CRLF.\r
- # Raise EOFError if the connection is closed\r
- def getline(self):\r
- line = self.file.readline()\r
- if self.debugging > 1:\r
- print '*get*', self.sanitize(line)\r
- if not line: raise EOFError\r
- if line[-2:] == CRLF: line = line[:-2]\r
- elif line[-1:] in CRLF: line = line[:-1]\r
- return line\r
-\r
- # Internal: get a response from the server, which may possibly\r
- # consist of multiple lines. Return a single string with no\r
- # trailing CRLF. If the response consists of multiple lines,\r
- # these are separated by '\n' characters in the string\r
- def getmultiline(self):\r
- line = self.getline()\r
- if line[3:4] == '-':\r
- code = line[:3]\r
- while 1:\r
- nextline = self.getline()\r
- line = line + ('\n' + nextline)\r
- if nextline[:3] == code and \\r
- nextline[3:4] != '-':\r
- break\r
- return line\r
-\r
- # Internal: get a response from the server.\r
- # Raise various errors if the response indicates an error\r
- def getresp(self):\r
- resp = self.getmultiline()\r
- if self.debugging: print '*resp*', self.sanitize(resp)\r
- self.lastresp = resp[:3]\r
- c = resp[:1]\r
- if c in ('1', '2', '3'):\r
- return resp\r
- if c == '4':\r
- raise error_temp, resp\r
- if c == '5':\r
- raise error_perm, resp\r
- raise error_proto, resp\r
-\r
- def voidresp(self):\r
- """Expect a response beginning with '2'."""\r
- resp = self.getresp()\r
- if resp[:1] != '2':\r
- raise error_reply, resp\r
- return resp\r
-\r
- def abort(self):\r
- '''Abort a file transfer. Uses out-of-band data.\r
- This does not follow the procedure from the RFC to send Telnet\r
- IP and Synch; that doesn't seem to work with the servers I've\r
- tried. Instead, just send the ABOR command as OOB data.'''\r
- line = 'ABOR' + CRLF\r
- if self.debugging > 1: print '*put urgent*', self.sanitize(line)\r
- self.sock.sendall(line, MSG_OOB)\r
- resp = self.getmultiline()\r
- if resp[:3] not in ('426', '225', '226'):\r
- raise error_proto, resp\r
-\r
- def sendcmd(self, cmd):\r
- '''Send a command and return the response.'''\r
- self.putcmd(cmd)\r
- return self.getresp()\r
-\r
- def voidcmd(self, cmd):\r
- """Send a command and expect a response beginning with '2'."""\r
- self.putcmd(cmd)\r
- return self.voidresp()\r
-\r
- def sendport(self, host, port):\r
- '''Send a PORT command with the current host and the given\r
- port number.\r
- '''\r
- hbytes = host.split('.')\r
- pbytes = [repr(port//256), repr(port%256)]\r
- bytes = hbytes + pbytes\r
- cmd = 'PORT ' + ','.join(bytes)\r
- return self.voidcmd(cmd)\r
-\r
- def sendeprt(self, host, port):\r
- '''Send a EPRT command with the current host and the given port number.'''\r
- af = 0\r
- if self.af == socket.AF_INET:\r
- af = 1\r
- if self.af == socket.AF_INET6:\r
- af = 2\r
- if af == 0:\r
- raise error_proto, 'unsupported address family'\r
- fields = ['', repr(af), host, repr(port), '']\r
- cmd = 'EPRT ' + '|'.join(fields)\r
- return self.voidcmd(cmd)\r
-\r
- def makeport(self):\r
- '''Create a new socket and send a PORT command for it.'''\r
- msg = "getaddrinfo returns an empty list"\r
- sock = None\r
- for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):\r
- af, socktype, proto, canonname, sa = res\r
- try:\r
- sock = socket.socket(af, socktype, proto)\r
- sock.bind(sa)\r
- except socket.error, msg:\r
- if sock:\r
- sock.close()\r
- sock = None\r
- continue\r
- break\r
- if not sock:\r
- raise socket.error, msg\r
- sock.listen(1)\r
- port = sock.getsockname()[1] # Get proper port\r
- host = self.sock.getsockname()[0] # Get proper host\r
- if self.af == socket.AF_INET:\r
- resp = self.sendport(host, port)\r
- else:\r
- resp = self.sendeprt(host, port)\r
- if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:\r
- sock.settimeout(self.timeout)\r
- return sock\r
-\r
- def makepasv(self):\r
- if self.af == socket.AF_INET:\r
- host, port = parse227(self.sendcmd('PASV'))\r
- else:\r
- host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername())\r
- return host, port\r
-\r
- def ntransfercmd(self, cmd, rest=None):\r
- """Initiate a transfer over the data connection.\r
-\r
- If the transfer is active, send a port command and the\r
- transfer command, and accept the connection. If the server is\r
- passive, send a pasv command, connect to it, and start the\r
- transfer command. Either way, return the socket for the\r
- connection and the expected size of the transfer. The\r
- expected size may be None if it could not be determined.\r
-\r
- Optional `rest' argument can be a string that is sent as the\r
- argument to a REST command. This is essentially a server\r
- marker used to tell the server to skip over any data up to the\r
- given marker.\r
- """\r
- size = None\r
- if self.passiveserver:\r
- host, port = self.makepasv()\r
- conn = socket.create_connection((host, port), self.timeout)\r
- if rest is not None:\r
- self.sendcmd("REST %s" % rest)\r
- resp = self.sendcmd(cmd)\r
- # Some servers apparently send a 200 reply to\r
- # a LIST or STOR command, before the 150 reply\r
- # (and way before the 226 reply). This seems to\r
- # be in violation of the protocol (which only allows\r
- # 1xx or error messages for LIST), so we just discard\r
- # this response.\r
- if resp[0] == '2':\r
- resp = self.getresp()\r
- if resp[0] != '1':\r
- raise error_reply, resp\r
- else:\r
- sock = self.makeport()\r
- if rest is not None:\r
- self.sendcmd("REST %s" % rest)\r
- resp = self.sendcmd(cmd)\r
- # See above.\r
- if resp[0] == '2':\r
- resp = self.getresp()\r
- if resp[0] != '1':\r
- raise error_reply, resp\r
- conn, sockaddr = sock.accept()\r
- if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:\r
- conn.settimeout(self.timeout)\r
- if resp[:3] == '150':\r
- # this is conditional in case we received a 125\r
- size = parse150(resp)\r
- return conn, size\r
-\r
- def transfercmd(self, cmd, rest=None):\r
- """Like ntransfercmd() but returns only the socket."""\r
- return self.ntransfercmd(cmd, rest)[0]\r
-\r
- def login(self, user = '', passwd = '', acct = ''):\r
- '''Login, default anonymous.'''\r
- if not user: user = 'anonymous'\r
- if not passwd: passwd = ''\r
- if not acct: acct = ''\r
- if user == 'anonymous' and passwd in ('', '-'):\r
- # If there is no anonymous ftp password specified\r
- # then we'll just use anonymous@\r
- # We don't send any other thing because:\r
- # - We want to remain anonymous\r
- # - We want to stop SPAM\r
- # - We don't want to let ftp sites to discriminate by the user,\r
- # host or country.\r
- passwd = passwd + 'anonymous@'\r
- resp = self.sendcmd('USER ' + user)\r
- if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd)\r
- if resp[0] == '3': resp = self.sendcmd('ACCT ' + acct)\r
- if resp[0] != '2':\r
- raise error_reply, resp\r
- return resp\r
-\r
- def retrbinary(self, cmd, callback, blocksize=8192, rest=None):\r
- """Retrieve data in binary mode. A new port is created for you.\r
-\r
- Args:\r
- cmd: A RETR command.\r
- callback: A single parameter callable to be called on each\r
- block of data read.\r
- blocksize: The maximum number of bytes to read from the\r
- socket at one time. [default: 8192]\r
- rest: Passed to transfercmd(). [default: None]\r
-\r
- Returns:\r
- The response code.\r
- """\r
- self.voidcmd('TYPE I')\r
- conn = self.transfercmd(cmd, rest)\r
- while 1:\r
- data = conn.recv(blocksize)\r
- if not data:\r
- break\r
- callback(data)\r
- conn.close()\r
- return self.voidresp()\r
-\r
- def retrlines(self, cmd, callback = None):\r
- """Retrieve data in line mode. A new port is created for you.\r
-\r
- Args:\r
- cmd: A RETR, LIST, NLST, or MLSD command.\r
- callback: An optional single parameter callable that is called\r
- for each line with the trailing CRLF stripped.\r
- [default: print_line()]\r
-\r
- Returns:\r
- The response code.\r
- """\r
- if callback is None: callback = print_line\r
- resp = self.sendcmd('TYPE A')\r
- conn = self.transfercmd(cmd)\r
- fp = conn.makefile('rb')\r
- while 1:\r
- line = fp.readline()\r
- if self.debugging > 2: print '*retr*', repr(line)\r
- if not line:\r
- break\r
- if line[-2:] == CRLF:\r
- line = line[:-2]\r
- elif line[-1:] == '\n':\r
- line = line[:-1]\r
- callback(line)\r
- fp.close()\r
- conn.close()\r
- return self.voidresp()\r
-\r
- def storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None):\r
- """Store a file in binary mode. A new port is created for you.\r
-\r
- Args:\r
- cmd: A STOR command.\r
- fp: A file-like object with a read(num_bytes) method.\r
- blocksize: The maximum data size to read from fp and send over\r
- the connection at once. [default: 8192]\r
- callback: An optional single parameter callable that is called on\r
- on each block of data after it is sent. [default: None]\r
- rest: Passed to transfercmd(). [default: None]\r
-\r
- Returns:\r
- The response code.\r
- """\r
- self.voidcmd('TYPE I')\r
- conn = self.transfercmd(cmd, rest)\r
- while 1:\r
- buf = fp.read(blocksize)\r
- if not buf: break\r
- conn.sendall(buf)\r
- if callback: callback(buf)\r
- conn.close()\r
- return self.voidresp()\r
-\r
- def storlines(self, cmd, fp, callback=None):\r
- """Store a file in line mode. A new port is created for you.\r
-\r
- Args:\r
- cmd: A STOR command.\r
- fp: A file-like object with a readline() method.\r
- callback: An optional single parameter callable that is called on\r
- on each line after it is sent. [default: None]\r
-\r
- Returns:\r
- The response code.\r
- """\r
- self.voidcmd('TYPE A')\r
- conn = self.transfercmd(cmd)\r
- while 1:\r
- buf = fp.readline()\r
- if not buf: break\r
- if buf[-2:] != CRLF:\r
- if buf[-1] in CRLF: buf = buf[:-1]\r
- buf = buf + CRLF\r
- conn.sendall(buf)\r
- if callback: callback(buf)\r
- conn.close()\r
- return self.voidresp()\r
-\r
- def acct(self, password):\r
- '''Send new account name.'''\r
- cmd = 'ACCT ' + password\r
- return self.voidcmd(cmd)\r
-\r
- def nlst(self, *args):\r
- '''Return a list of files in a given directory (default the current).'''\r
- cmd = 'NLST'\r
- for arg in args:\r
- cmd = cmd + (' ' + arg)\r
- files = []\r
- self.retrlines(cmd, files.append)\r
- return files\r
-\r
- def dir(self, *args):\r
- '''List a directory in long form.\r
- By default list current directory to stdout.\r
- Optional last argument is callback function; all\r
- non-empty arguments before it are concatenated to the\r
- LIST command. (This *should* only be used for a pathname.)'''\r
- cmd = 'LIST'\r
- func = None\r
- if args[-1:] and type(args[-1]) != type(''):\r
- args, func = args[:-1], args[-1]\r
- for arg in args:\r
- if arg:\r
- cmd = cmd + (' ' + arg)\r
- self.retrlines(cmd, func)\r
-\r
- def rename(self, fromname, toname):\r
- '''Rename a file.'''\r
- resp = self.sendcmd('RNFR ' + fromname)\r
- if resp[0] != '3':\r
- raise error_reply, resp\r
- return self.voidcmd('RNTO ' + toname)\r
-\r
- def delete(self, filename):\r
- '''Delete a file.'''\r
- resp = self.sendcmd('DELE ' + filename)\r
- if resp[:3] in ('250', '200'):\r
- return resp\r
- else:\r
- raise error_reply, resp\r
-\r
- def cwd(self, dirname):\r
- '''Change to a directory.'''\r
- if dirname == '..':\r
- try:\r
- return self.voidcmd('CDUP')\r
- except error_perm, msg:\r
- if msg.args[0][:3] != '500':\r
- raise\r
- elif dirname == '':\r
- dirname = '.' # does nothing, but could return error\r
- cmd = 'CWD ' + dirname\r
- return self.voidcmd(cmd)\r
-\r
- def size(self, filename):\r
- '''Retrieve the size of a file.'''\r
- # The SIZE command is defined in RFC-3659\r
- resp = self.sendcmd('SIZE ' + filename)\r
- if resp[:3] == '213':\r
- s = resp[3:].strip()\r
- try:\r
- return int(s)\r
- except (OverflowError, ValueError):\r
- return long(s)\r
-\r
- def mkd(self, dirname):\r
- '''Make a directory, return its full pathname.'''\r
- resp = self.sendcmd('MKD ' + dirname)\r
- return parse257(resp)\r
-\r
- def rmd(self, dirname):\r
- '''Remove a directory.'''\r
- return self.voidcmd('RMD ' + dirname)\r
-\r
- def pwd(self):\r
- '''Return current working directory.'''\r
- resp = self.sendcmd('PWD')\r
- return parse257(resp)\r
-\r
- def quit(self):\r
- '''Quit, and close the connection.'''\r
- resp = self.voidcmd('QUIT')\r
- self.close()\r
- return resp\r
-\r
- def close(self):\r
- '''Close the connection without assuming anything about it.'''\r
- if self.file:\r
- self.file.close()\r
- self.sock.close()\r
- self.file = self.sock = None\r
-\r
-\r
-try:\r
- import ssl\r
-except ImportError:\r
- pass\r
-else:\r
- class FTP_TLS(FTP):\r
- '''A FTP subclass which adds TLS support to FTP as described\r
- in RFC-4217.\r
-\r
- Connect as usual to port 21 implicitly securing the FTP control\r
- connection before authenticating.\r
-\r
- Securing the data connection requires user to explicitly ask\r
- for it by calling prot_p() method.\r
-\r
- Usage example:\r
- >>> from ftplib import FTP_TLS\r
- >>> ftps = FTP_TLS('ftp.python.org')\r
- >>> ftps.login() # login anonymously previously securing control channel\r
- '230 Guest login ok, access restrictions apply.'\r
- >>> ftps.prot_p() # switch to secure data connection\r
- '200 Protection level set to P'\r
- >>> ftps.retrlines('LIST') # list directory content securely\r
- total 9\r
- drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .\r
- drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..\r
- drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin\r
- drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc\r
- d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming\r
- drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib\r
- drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub\r
- drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr\r
- -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg\r
- '226 Transfer complete.'\r
- >>> ftps.quit()\r
- '221 Goodbye.'\r
- >>>\r
- '''\r
- ssl_version = ssl.PROTOCOL_TLSv1\r
-\r
- def __init__(self, host='', user='', passwd='', acct='', keyfile=None,\r
- certfile=None, timeout=_GLOBAL_DEFAULT_TIMEOUT):\r
- self.keyfile = keyfile\r
- self.certfile = certfile\r
- self._prot_p = False\r
- FTP.__init__(self, host, user, passwd, acct, timeout)\r
-\r
- def login(self, user='', passwd='', acct='', secure=True):\r
- if secure and not isinstance(self.sock, ssl.SSLSocket):\r
- self.auth()\r
- return FTP.login(self, user, passwd, acct)\r
-\r
- def auth(self):\r
- '''Set up secure control connection by using TLS/SSL.'''\r
- if isinstance(self.sock, ssl.SSLSocket):\r
- raise ValueError("Already using TLS")\r
- if self.ssl_version == ssl.PROTOCOL_TLSv1:\r
- resp = self.voidcmd('AUTH TLS')\r
- else:\r
- resp = self.voidcmd('AUTH SSL')\r
- self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile,\r
- ssl_version=self.ssl_version)\r
- self.file = self.sock.makefile(mode='rb')\r
- return resp\r
-\r
- def prot_p(self):\r
- '''Set up secure data connection.'''\r
- # PROT defines whether or not the data channel is to be protected.\r
- # Though RFC-2228 defines four possible protection levels,\r
- # RFC-4217 only recommends two, Clear and Private.\r
- # Clear (PROT C) means that no security is to be used on the\r
- # data-channel, Private (PROT P) means that the data-channel\r
- # should be protected by TLS.\r
- # PBSZ command MUST still be issued, but must have a parameter of\r
- # '0' to indicate that no buffering is taking place and the data\r
- # connection should not be encapsulated.\r
- self.voidcmd('PBSZ 0')\r
- resp = self.voidcmd('PROT P')\r
- self._prot_p = True\r
- return resp\r
-\r
- def prot_c(self):\r
- '''Set up clear text data connection.'''\r
- resp = self.voidcmd('PROT C')\r
- self._prot_p = False\r
- return resp\r
-\r
- # --- Overridden FTP methods\r
-\r
- def ntransfercmd(self, cmd, rest=None):\r
- conn, size = FTP.ntransfercmd(self, cmd, rest)\r
- if self._prot_p:\r
- conn = ssl.wrap_socket(conn, self.keyfile, self.certfile,\r
- ssl_version=self.ssl_version)\r
- return conn, size\r
-\r
- def retrbinary(self, cmd, callback, blocksize=8192, rest=None):\r
- self.voidcmd('TYPE I')\r
- conn = self.transfercmd(cmd, rest)\r
- try:\r
- while 1:\r
- data = conn.recv(blocksize)\r
- if not data:\r
- break\r
- callback(data)\r
- # shutdown ssl layer\r
- if isinstance(conn, ssl.SSLSocket):\r
- conn.unwrap()\r
- finally:\r
- conn.close()\r
- return self.voidresp()\r
-\r
- def retrlines(self, cmd, callback = None):\r
- if callback is None: callback = print_line\r
- resp = self.sendcmd('TYPE A')\r
- conn = self.transfercmd(cmd)\r
- fp = conn.makefile('rb')\r
- try:\r
- while 1:\r
- line = fp.readline()\r
- if self.debugging > 2: print '*retr*', repr(line)\r
- if not line:\r
- break\r
- if line[-2:] == CRLF:\r
- line = line[:-2]\r
- elif line[-1:] == '\n':\r
- line = line[:-1]\r
- callback(line)\r
- # shutdown ssl layer\r
- if isinstance(conn, ssl.SSLSocket):\r
- conn.unwrap()\r
- finally:\r
- fp.close()\r
- conn.close()\r
- return self.voidresp()\r
-\r
- def storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None):\r
- self.voidcmd('TYPE I')\r
- conn = self.transfercmd(cmd, rest)\r
- try:\r
- while 1:\r
- buf = fp.read(blocksize)\r
- if not buf: break\r
- conn.sendall(buf)\r
- if callback: callback(buf)\r
- # shutdown ssl layer\r
- if isinstance(conn, ssl.SSLSocket):\r
- conn.unwrap()\r
- finally:\r
- conn.close()\r
- return self.voidresp()\r
-\r
- def storlines(self, cmd, fp, callback=None):\r
- self.voidcmd('TYPE A')\r
- conn = self.transfercmd(cmd)\r
- try:\r
- while 1:\r
- buf = fp.readline()\r
- if not buf: break\r
- if buf[-2:] != CRLF:\r
- if buf[-1] in CRLF: buf = buf[:-1]\r
- buf = buf + CRLF\r
- conn.sendall(buf)\r
- if callback: callback(buf)\r
- # shutdown ssl layer\r
- if isinstance(conn, ssl.SSLSocket):\r
- conn.unwrap()\r
- finally:\r
- conn.close()\r
- return self.voidresp()\r
-\r
- __all__.append('FTP_TLS')\r
- all_errors = (Error, IOError, EOFError, ssl.SSLError)\r
-\r
-\r
-_150_re = None\r
-\r
-def parse150(resp):\r
- '''Parse the '150' response for a RETR request.\r
- Returns the expected transfer size or None; size is not guaranteed to\r
- be present in the 150 message.\r
- '''\r
- if resp[:3] != '150':\r
- raise error_reply, resp\r
- global _150_re\r
- if _150_re is None:\r
- import re\r
- _150_re = re.compile("150 .* \((\d+) bytes\)", re.IGNORECASE)\r
- m = _150_re.match(resp)\r
- if not m:\r
- return None\r
- s = m.group(1)\r
- try:\r
- return int(s)\r
- except (OverflowError, ValueError):\r
- return long(s)\r
-\r
-\r
-_227_re = None\r
-\r
-def parse227(resp):\r
- '''Parse the '227' response for a PASV request.\r
- Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'\r
- Return ('host.addr.as.numbers', port#) tuple.'''\r
-\r
- if resp[:3] != '227':\r
- raise error_reply, resp\r
- global _227_re\r
- if _227_re is None:\r
- import re\r
- _227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)')\r
- m = _227_re.search(resp)\r
- if not m:\r
- raise error_proto, resp\r
- numbers = m.groups()\r
- host = '.'.join(numbers[:4])\r
- port = (int(numbers[4]) << 8) + int(numbers[5])\r
- return host, port\r
-\r
-\r
-def parse229(resp, peer):\r
- '''Parse the '229' response for a EPSV request.\r
- Raises error_proto if it does not contain '(|||port|)'\r
- Return ('host.addr.as.numbers', port#) tuple.'''\r
-\r
- if resp[:3] != '229':\r
- raise error_reply, resp\r
- left = resp.find('(')\r
- if left < 0: raise error_proto, resp\r
- right = resp.find(')', left + 1)\r
- if right < 0:\r
- raise error_proto, resp # should contain '(|||port|)'\r
- if resp[left + 1] != resp[right - 1]:\r
- raise error_proto, resp\r
- parts = resp[left + 1:right].split(resp[left+1])\r
- if len(parts) != 5:\r
- raise error_proto, resp\r
- host = peer[0]\r
- port = int(parts[3])\r
- return host, port\r
-\r
-\r
-def parse257(resp):\r
- '''Parse the '257' response for a MKD or PWD request.\r
- This is a response to a MKD or PWD request: a directory name.\r
- Returns the directoryname in the 257 reply.'''\r
-\r
- if resp[:3] != '257':\r
- raise error_reply, resp\r
- if resp[3:5] != ' "':\r
- return '' # Not compliant to RFC 959, but UNIX ftpd does this\r
- dirname = ''\r
- i = 5\r
- n = len(resp)\r
- while i < n:\r
- c = resp[i]\r
- i = i+1\r
- if c == '"':\r
- if i >= n or resp[i] != '"':\r
- break\r
- i = i+1\r
- dirname = dirname + c\r
- return dirname\r
-\r
-\r
-def print_line(line):\r
- '''Default retrlines callback to print a line.'''\r
- print line\r
-\r
-\r
-def ftpcp(source, sourcename, target, targetname = '', type = 'I'):\r
- '''Copy file from one FTP-instance to another.'''\r
- if not targetname: targetname = sourcename\r
- type = 'TYPE ' + type\r
- source.voidcmd(type)\r
- target.voidcmd(type)\r
- sourcehost, sourceport = parse227(source.sendcmd('PASV'))\r
- target.sendport(sourcehost, sourceport)\r
- # RFC 959: the user must "listen" [...] BEFORE sending the\r
- # transfer request.\r
- # So: STOR before RETR, because here the target is a "user".\r
- treply = target.sendcmd('STOR ' + targetname)\r
- if treply[:3] not in ('125', '150'): raise error_proto # RFC 959\r
- sreply = source.sendcmd('RETR ' + sourcename)\r
- if sreply[:3] not in ('125', '150'): raise error_proto # RFC 959\r
- source.voidresp()\r
- target.voidresp()\r
-\r
-\r
-class Netrc:\r
- """Class to parse & provide access to 'netrc' format files.\r
-\r
- See the netrc(4) man page for information on the file format.\r
-\r
- WARNING: This class is obsolete -- use module netrc instead.\r
-\r
- """\r
- __defuser = None\r
- __defpasswd = None\r
- __defacct = None\r
-\r
- def __init__(self, filename=None):\r
- if filename is None:\r
- if "HOME" in os.environ:\r
- filename = os.path.join(os.environ["HOME"],\r
- ".netrc")\r
- else:\r
- raise IOError, \\r
- "specify file to load or set $HOME"\r
- self.__hosts = {}\r
- self.__macros = {}\r
- fp = open(filename, "r")\r
- in_macro = 0\r
- while 1:\r
- line = fp.readline()\r
- if not line: break\r
- if in_macro and line.strip():\r
- macro_lines.append(line)\r
- continue\r
- elif in_macro:\r
- self.__macros[macro_name] = tuple(macro_lines)\r
- in_macro = 0\r
- words = line.split()\r
- host = user = passwd = acct = None\r
- default = 0\r
- i = 0\r
- while i < len(words):\r
- w1 = words[i]\r
- if i+1 < len(words):\r
- w2 = words[i + 1]\r
- else:\r
- w2 = None\r
- if w1 == 'default':\r
- default = 1\r
- elif w1 == 'machine' and w2:\r
- host = w2.lower()\r
- i = i + 1\r
- elif w1 == 'login' and w2:\r
- user = w2\r
- i = i + 1\r
- elif w1 == 'password' and w2:\r
- passwd = w2\r
- i = i + 1\r
- elif w1 == 'account' and w2:\r
- acct = w2\r
- i = i + 1\r
- elif w1 == 'macdef' and w2:\r
- macro_name = w2\r
- macro_lines = []\r
- in_macro = 1\r
- break\r
- i = i + 1\r
- if default:\r
- self.__defuser = user or self.__defuser\r
- self.__defpasswd = passwd or self.__defpasswd\r
- self.__defacct = acct or self.__defacct\r
- if host:\r
- if host in self.__hosts:\r
- ouser, opasswd, oacct = \\r
- self.__hosts[host]\r
- user = user or ouser\r
- passwd = passwd or opasswd\r
- acct = acct or oacct\r
- self.__hosts[host] = user, passwd, acct\r
- fp.close()\r
-\r
- def get_hosts(self):\r
- """Return a list of hosts mentioned in the .netrc file."""\r
- return self.__hosts.keys()\r
-\r
- def get_account(self, host):\r
- """Returns login information for the named host.\r
-\r
- The return value is a triple containing userid,\r
- password, and the accounting field.\r
-\r
- """\r
- host = host.lower()\r
- user = passwd = acct = None\r
- if host in self.__hosts:\r
- user, passwd, acct = self.__hosts[host]\r
- user = user or self.__defuser\r
- passwd = passwd or self.__defpasswd\r
- acct = acct or self.__defacct\r
- return user, passwd, acct\r
-\r
- def get_macros(self):\r
- """Return a list of all defined macro names."""\r
- return self.__macros.keys()\r
-\r
- def get_macro(self, macro):\r
- """Return a sequence of lines which define a named macro."""\r
- return self.__macros[macro]\r
-\r
-\r
-\r
-def test():\r
- '''Test program.\r
- Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...\r
-\r
- -d dir\r
- -l list\r
- -p password\r
- '''\r
-\r
- if len(sys.argv) < 2:\r
- print test.__doc__\r
- sys.exit(0)\r
-\r
- debugging = 0\r
- rcfile = None\r
- while sys.argv[1] == '-d':\r
- debugging = debugging+1\r
- del sys.argv[1]\r
- if sys.argv[1][:2] == '-r':\r
- # get name of alternate ~/.netrc file:\r
- rcfile = sys.argv[1][2:]\r
- del sys.argv[1]\r
- host = sys.argv[1]\r
- ftp = FTP(host)\r
- ftp.set_debuglevel(debugging)\r
- userid = passwd = acct = ''\r
- try:\r
- netrc = Netrc(rcfile)\r
- except IOError:\r
- if rcfile is not None:\r
- sys.stderr.write("Could not open account file"\r
- " -- using anonymous login.")\r
- else:\r
- try:\r
- userid, passwd, acct = netrc.get_account(host)\r
- except KeyError:\r
- # no account for host\r
- sys.stderr.write(\r
- "No account -- using anonymous login.")\r
- ftp.login(userid, passwd, acct)\r
- for file in sys.argv[2:]:\r
- if file[:2] == '-l':\r
- ftp.dir(file[2:])\r
- elif file[:2] == '-d':\r
- cmd = 'CWD'\r
- if file[2:]: cmd = cmd + ' ' + file[2:]\r
- resp = ftp.sendcmd(cmd)\r
- elif file == '-p':\r
- ftp.set_pasv(not ftp.passiveserver)\r
- else:\r
- ftp.retrbinary('RETR ' + file, \\r
- sys.stdout.write, 1024)\r
- ftp.quit()\r
-\r
-\r
-if __name__ == '__main__':\r
- test()\r