ยปCore Development>Code coverage>Lib/ftplib.py

Python code coverage for Lib/ftplib.py

#countcontent
1n/a"""An FTP client class and some helper functions.
2n/a
3n/aBased on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
4n/a
5n/aExample:
6n/a
7n/a>>> from ftplib import FTP
8n/a>>> ftp = FTP('ftp.python.org') # connect to host, default port
9n/a>>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
10n/a'230 Guest login ok, access restrictions apply.'
11n/a>>> ftp.retrlines('LIST') # list directory contents
12n/atotal 9
13n/adrwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
14n/adrwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
15n/adrwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
16n/adrwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
17n/ad-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
18n/adrwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
19n/adrwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
20n/adrwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
21n/a-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
22n/a'226 Transfer complete.'
23n/a>>> ftp.quit()
24n/a'221 Goodbye.'
25n/a>>>
26n/a
27n/aA nice test that reveals some of the network dialogue would be:
28n/apython ftplib.py -d localhost -l -p -l
29n/a"""
30n/a
31n/a#
32n/a# Changes and improvements suggested by Steve Majewski.
33n/a# Modified by Jack to work on the mac.
34n/a# Modified by Siebren to support docstrings and PASV.
35n/a# Modified by Phil Schwartz to add storbinary and storlines callbacks.
36n/a# Modified by Giampaolo Rodola' to add TLS support.
37n/a#
38n/a
39n/aimport sys
40n/aimport socket
41n/afrom socket import _GLOBAL_DEFAULT_TIMEOUT
42n/a
43n/a__all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto",
44n/a "all_errors"]
45n/a
46n/a# Magic number from <socket.h>
47n/aMSG_OOB = 0x1 # Process data out of band
48n/a
49n/a
50n/a# The standard FTP server control port
51n/aFTP_PORT = 21
52n/a# The sizehint parameter passed to readline() calls
53n/aMAXLINE = 8192
54n/a
55n/a
56n/a# Exception raised when an error or invalid response is received
57n/aclass Error(Exception): pass
58n/aclass error_reply(Error): pass # unexpected [123]xx reply
59n/aclass error_temp(Error): pass # 4xx errors
60n/aclass error_perm(Error): pass # 5xx errors
61n/aclass error_proto(Error): pass # response does not begin with [1-5]
62n/a
63n/a
64n/a# All exceptions (hopefully) that may be raised here and that aren't
65n/a# (always) programming errors on our side
66n/aall_errors = (Error, OSError, EOFError)
67n/a
68n/a
69n/a# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
70n/aCRLF = '\r\n'
71n/aB_CRLF = b'\r\n'
72n/a
73n/a# The class itself
74n/aclass FTP:
75n/a
76n/a '''An FTP client class.
77n/a
78n/a To create a connection, call the class using these arguments:
79n/a host, user, passwd, acct, timeout
80n/a
81n/a The first four arguments are all strings, and have default value ''.
82n/a timeout must be numeric and defaults to None if not passed,
83n/a meaning that no timeout will be set on any ftp socket(s)
84n/a If a timeout is passed, then this is now the default timeout for all ftp
85n/a socket operations for this instance.
86n/a
87n/a Then use self.connect() with optional host and port argument.
88n/a
89n/a To download a file, use ftp.retrlines('RETR ' + filename),
90n/a or ftp.retrbinary() with slightly different arguments.
91n/a To upload a file, use ftp.storlines() or ftp.storbinary(),
92n/a which have an open file as argument (see their definitions
93n/a below for details).
94n/a The download/upload functions first issue appropriate TYPE
95n/a and PORT or PASV commands.
96n/a '''
97n/a
98n/a debugging = 0
99n/a host = ''
100n/a port = FTP_PORT
101n/a maxline = MAXLINE
102n/a sock = None
103n/a file = None
104n/a welcome = None
105n/a passiveserver = 1
106n/a encoding = "latin-1"
107n/a
108n/a # Initialization method (called by class instantiation).
109n/a # Initialize host to localhost, port to standard ftp port
110n/a # Optional arguments are host (for connect()),
111n/a # and user, passwd, acct (for login())
112n/a def __init__(self, host='', user='', passwd='', acct='',
113n/a timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
114n/a self.source_address = source_address
115n/a self.timeout = timeout
116n/a if host:
117n/a self.connect(host)
118n/a if user:
119n/a self.login(user, passwd, acct)
120n/a
121n/a def __enter__(self):
122n/a return self
123n/a
124n/a # Context management protocol: try to quit() if active
125n/a def __exit__(self, *args):
126n/a if self.sock is not None:
127n/a try:
128n/a self.quit()
129n/a except (OSError, EOFError):
130n/a pass
131n/a finally:
132n/a if self.sock is not None:
133n/a self.close()
134n/a
135n/a def connect(self, host='', port=0, timeout=-999, source_address=None):
136n/a '''Connect to host. Arguments are:
137n/a - host: hostname to connect to (string, default previous host)
138n/a - port: port to connect to (integer, default previous port)
139n/a - timeout: the timeout to set against the ftp socket(s)
140n/a - source_address: a 2-tuple (host, port) for the socket to bind
141n/a to as its source address before connecting.
142n/a '''
143n/a if host != '':
144n/a self.host = host
145n/a if port > 0:
146n/a self.port = port
147n/a if timeout != -999:
148n/a self.timeout = timeout
149n/a if source_address is not None:
150n/a self.source_address = source_address
151n/a self.sock = socket.create_connection((self.host, self.port), self.timeout,
152n/a source_address=self.source_address)
153n/a self.af = self.sock.family
154n/a self.file = self.sock.makefile('r', encoding=self.encoding)
155n/a self.welcome = self.getresp()
156n/a return self.welcome
157n/a
158n/a def getwelcome(self):
159n/a '''Get the welcome message from the server.
160n/a (this is read and squirreled away by connect())'''
161n/a if self.debugging:
162n/a print('*welcome*', self.sanitize(self.welcome))
163n/a return self.welcome
164n/a
165n/a def set_debuglevel(self, level):
166n/a '''Set the debugging level.
167n/a The required argument level means:
168n/a 0: no debugging output (default)
169n/a 1: print commands and responses but not body text etc.
170n/a 2: also print raw lines read and sent before stripping CR/LF'''
171n/a self.debugging = level
172n/a debug = set_debuglevel
173n/a
174n/a def set_pasv(self, val):
175n/a '''Use passive or active mode for data transfers.
176n/a With a false argument, use the normal PORT mode,
177n/a With a true argument, use the PASV command.'''
178n/a self.passiveserver = val
179n/a
180n/a # Internal: "sanitize" a string for printing
181n/a def sanitize(self, s):
182n/a if s[:5] in {'pass ', 'PASS '}:
183n/a i = len(s.rstrip('\r\n'))
184n/a s = s[:5] + '*'*(i-5) + s[i:]
185n/a return repr(s)
186n/a
187n/a # Internal: send one line to the server, appending CRLF
188n/a def putline(self, line):
189n/a line = line + CRLF
190n/a if self.debugging > 1:
191n/a print('*put*', self.sanitize(line))
192n/a self.sock.sendall(line.encode(self.encoding))
193n/a
194n/a # Internal: send one command to the server (through putline())
195n/a def putcmd(self, line):
196n/a if self.debugging: print('*cmd*', self.sanitize(line))
197n/a self.putline(line)
198n/a
199n/a # Internal: return one line from the server, stripping CRLF.
200n/a # Raise EOFError if the connection is closed
201n/a def getline(self):
202n/a line = self.file.readline(self.maxline + 1)
203n/a if len(line) > self.maxline:
204n/a raise Error("got more than %d bytes" % self.maxline)
205n/a if self.debugging > 1:
206n/a print('*get*', self.sanitize(line))
207n/a if not line:
208n/a raise EOFError
209n/a if line[-2:] == CRLF:
210n/a line = line[:-2]
211n/a elif line[-1:] in CRLF:
212n/a line = line[:-1]
213n/a return line
214n/a
215n/a # Internal: get a response from the server, which may possibly
216n/a # consist of multiple lines. Return a single string with no
217n/a # trailing CRLF. If the response consists of multiple lines,
218n/a # these are separated by '\n' characters in the string
219n/a def getmultiline(self):
220n/a line = self.getline()
221n/a if line[3:4] == '-':
222n/a code = line[:3]
223n/a while 1:
224n/a nextline = self.getline()
225n/a line = line + ('\n' + nextline)
226n/a if nextline[:3] == code and \
227n/a nextline[3:4] != '-':
228n/a break
229n/a return line
230n/a
231n/a # Internal: get a response from the server.
232n/a # Raise various errors if the response indicates an error
233n/a def getresp(self):
234n/a resp = self.getmultiline()
235n/a if self.debugging:
236n/a print('*resp*', self.sanitize(resp))
237n/a self.lastresp = resp[:3]
238n/a c = resp[:1]
239n/a if c in {'1', '2', '3'}:
240n/a return resp
241n/a if c == '4':
242n/a raise error_temp(resp)
243n/a if c == '5':
244n/a raise error_perm(resp)
245n/a raise error_proto(resp)
246n/a
247n/a def voidresp(self):
248n/a """Expect a response beginning with '2'."""
249n/a resp = self.getresp()
250n/a if resp[:1] != '2':
251n/a raise error_reply(resp)
252n/a return resp
253n/a
254n/a def abort(self):
255n/a '''Abort a file transfer. Uses out-of-band data.
256n/a This does not follow the procedure from the RFC to send Telnet
257n/a IP and Synch; that doesn't seem to work with the servers I've
258n/a tried. Instead, just send the ABOR command as OOB data.'''
259n/a line = b'ABOR' + B_CRLF
260n/a if self.debugging > 1:
261n/a print('*put urgent*', self.sanitize(line))
262n/a self.sock.sendall(line, MSG_OOB)
263n/a resp = self.getmultiline()
264n/a if resp[:3] not in {'426', '225', '226'}:
265n/a raise error_proto(resp)
266n/a return resp
267n/a
268n/a def sendcmd(self, cmd):
269n/a '''Send a command and return the response.'''
270n/a self.putcmd(cmd)
271n/a return self.getresp()
272n/a
273n/a def voidcmd(self, cmd):
274n/a """Send a command and expect a response beginning with '2'."""
275n/a self.putcmd(cmd)
276n/a return self.voidresp()
277n/a
278n/a def sendport(self, host, port):
279n/a '''Send a PORT command with the current host and the given
280n/a port number.
281n/a '''
282n/a hbytes = host.split('.')
283n/a pbytes = [repr(port//256), repr(port%256)]
284n/a bytes = hbytes + pbytes
285n/a cmd = 'PORT ' + ','.join(bytes)
286n/a return self.voidcmd(cmd)
287n/a
288n/a def sendeprt(self, host, port):
289n/a '''Send an EPRT command with the current host and the given port number.'''
290n/a af = 0
291n/a if self.af == socket.AF_INET:
292n/a af = 1
293n/a if self.af == socket.AF_INET6:
294n/a af = 2
295n/a if af == 0:
296n/a raise error_proto('unsupported address family')
297n/a fields = ['', repr(af), host, repr(port), '']
298n/a cmd = 'EPRT ' + '|'.join(fields)
299n/a return self.voidcmd(cmd)
300n/a
301n/a def makeport(self):
302n/a '''Create a new socket and send a PORT command for it.'''
303n/a err = None
304n/a sock = None
305n/a for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
306n/a af, socktype, proto, canonname, sa = res
307n/a try:
308n/a sock = socket.socket(af, socktype, proto)
309n/a sock.bind(sa)
310n/a except OSError as _:
311n/a err = _
312n/a if sock:
313n/a sock.close()
314n/a sock = None
315n/a continue
316n/a break
317n/a if sock is None:
318n/a if err is not None:
319n/a raise err
320n/a else:
321n/a raise OSError("getaddrinfo returns an empty list")
322n/a sock.listen(1)
323n/a port = sock.getsockname()[1] # Get proper port
324n/a host = self.sock.getsockname()[0] # Get proper host
325n/a if self.af == socket.AF_INET:
326n/a resp = self.sendport(host, port)
327n/a else:
328n/a resp = self.sendeprt(host, port)
329n/a if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
330n/a sock.settimeout(self.timeout)
331n/a return sock
332n/a
333n/a def makepasv(self):
334n/a if self.af == socket.AF_INET:
335n/a host, port = parse227(self.sendcmd('PASV'))
336n/a else:
337n/a host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
338n/a return host, port
339n/a
340n/a def ntransfercmd(self, cmd, rest=None):
341n/a """Initiate a transfer over the data connection.
342n/a
343n/a If the transfer is active, send a port command and the
344n/a transfer command, and accept the connection. If the server is
345n/a passive, send a pasv command, connect to it, and start the
346n/a transfer command. Either way, return the socket for the
347n/a connection and the expected size of the transfer. The
348n/a expected size may be None if it could not be determined.
349n/a
350n/a Optional `rest' argument can be a string that is sent as the
351n/a argument to a REST command. This is essentially a server
352n/a marker used to tell the server to skip over any data up to the
353n/a given marker.
354n/a """
355n/a size = None
356n/a if self.passiveserver:
357n/a host, port = self.makepasv()
358n/a conn = socket.create_connection((host, port), self.timeout,
359n/a source_address=self.source_address)
360n/a try:
361n/a if rest is not None:
362n/a self.sendcmd("REST %s" % rest)
363n/a resp = self.sendcmd(cmd)
364n/a # Some servers apparently send a 200 reply to
365n/a # a LIST or STOR command, before the 150 reply
366n/a # (and way before the 226 reply). This seems to
367n/a # be in violation of the protocol (which only allows
368n/a # 1xx or error messages for LIST), so we just discard
369n/a # this response.
370n/a if resp[0] == '2':
371n/a resp = self.getresp()
372n/a if resp[0] != '1':
373n/a raise error_reply(resp)
374n/a except:
375n/a conn.close()
376n/a raise
377n/a else:
378n/a with self.makeport() as sock:
379n/a if rest is not None:
380n/a self.sendcmd("REST %s" % rest)
381n/a resp = self.sendcmd(cmd)
382n/a # See above.
383n/a if resp[0] == '2':
384n/a resp = self.getresp()
385n/a if resp[0] != '1':
386n/a raise error_reply(resp)
387n/a conn, sockaddr = sock.accept()
388n/a if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
389n/a conn.settimeout(self.timeout)
390n/a if resp[:3] == '150':
391n/a # this is conditional in case we received a 125
392n/a size = parse150(resp)
393n/a return conn, size
394n/a
395n/a def transfercmd(self, cmd, rest=None):
396n/a """Like ntransfercmd() but returns only the socket."""
397n/a return self.ntransfercmd(cmd, rest)[0]
398n/a
399n/a def login(self, user = '', passwd = '', acct = ''):
400n/a '''Login, default anonymous.'''
401n/a if not user:
402n/a user = 'anonymous'
403n/a if not passwd:
404n/a passwd = ''
405n/a if not acct:
406n/a acct = ''
407n/a if user == 'anonymous' and passwd in {'', '-'}:
408n/a # If there is no anonymous ftp password specified
409n/a # then we'll just use anonymous@
410n/a # We don't send any other thing because:
411n/a # - We want to remain anonymous
412n/a # - We want to stop SPAM
413n/a # - We don't want to let ftp sites to discriminate by the user,
414n/a # host or country.
415n/a passwd = passwd + 'anonymous@'
416n/a resp = self.sendcmd('USER ' + user)
417n/a if resp[0] == '3':
418n/a resp = self.sendcmd('PASS ' + passwd)
419n/a if resp[0] == '3':
420n/a resp = self.sendcmd('ACCT ' + acct)
421n/a if resp[0] != '2':
422n/a raise error_reply(resp)
423n/a return resp
424n/a
425n/a def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
426n/a """Retrieve data in binary mode. A new port is created for you.
427n/a
428n/a Args:
429n/a cmd: A RETR command.
430n/a callback: A single parameter callable to be called on each
431n/a block of data read.
432n/a blocksize: The maximum number of bytes to read from the
433n/a socket at one time. [default: 8192]
434n/a rest: Passed to transfercmd(). [default: None]
435n/a
436n/a Returns:
437n/a The response code.
438n/a """
439n/a self.voidcmd('TYPE I')
440n/a with self.transfercmd(cmd, rest) as conn:
441n/a while 1:
442n/a data = conn.recv(blocksize)
443n/a if not data:
444n/a break
445n/a callback(data)
446n/a # shutdown ssl layer
447n/a if _SSLSocket is not None and isinstance(conn, _SSLSocket):
448n/a conn.unwrap()
449n/a return self.voidresp()
450n/a
451n/a def retrlines(self, cmd, callback = None):
452n/a """Retrieve data in line mode. A new port is created for you.
453n/a
454n/a Args:
455n/a cmd: A RETR, LIST, or NLST command.
456n/a callback: An optional single parameter callable that is called
457n/a for each line with the trailing CRLF stripped.
458n/a [default: print_line()]
459n/a
460n/a Returns:
461n/a The response code.
462n/a """
463n/a if callback is None:
464n/a callback = print_line
465n/a resp = self.sendcmd('TYPE A')
466n/a with self.transfercmd(cmd) as conn, \
467n/a conn.makefile('r', encoding=self.encoding) as fp:
468n/a while 1:
469n/a line = fp.readline(self.maxline + 1)
470n/a if len(line) > self.maxline:
471n/a raise Error("got more than %d bytes" % self.maxline)
472n/a if self.debugging > 2:
473n/a print('*retr*', repr(line))
474n/a if not line:
475n/a break
476n/a if line[-2:] == CRLF:
477n/a line = line[:-2]
478n/a elif line[-1:] == '\n':
479n/a line = line[:-1]
480n/a callback(line)
481n/a # shutdown ssl layer
482n/a if _SSLSocket is not None and isinstance(conn, _SSLSocket):
483n/a conn.unwrap()
484n/a return self.voidresp()
485n/a
486n/a def storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None):
487n/a """Store a file in binary mode. A new port is created for you.
488n/a
489n/a Args:
490n/a cmd: A STOR command.
491n/a fp: A file-like object with a read(num_bytes) method.
492n/a blocksize: The maximum data size to read from fp and send over
493n/a the connection at once. [default: 8192]
494n/a callback: An optional single parameter callable that is called on
495n/a each block of data after it is sent. [default: None]
496n/a rest: Passed to transfercmd(). [default: None]
497n/a
498n/a Returns:
499n/a The response code.
500n/a """
501n/a self.voidcmd('TYPE I')
502n/a with self.transfercmd(cmd, rest) as conn:
503n/a while 1:
504n/a buf = fp.read(blocksize)
505n/a if not buf:
506n/a break
507n/a conn.sendall(buf)
508n/a if callback:
509n/a callback(buf)
510n/a # shutdown ssl layer
511n/a if _SSLSocket is not None and isinstance(conn, _SSLSocket):
512n/a conn.unwrap()
513n/a return self.voidresp()
514n/a
515n/a def storlines(self, cmd, fp, callback=None):
516n/a """Store a file in line mode. A new port is created for you.
517n/a
518n/a Args:
519n/a cmd: A STOR command.
520n/a fp: A file-like object with a readline() method.
521n/a callback: An optional single parameter callable that is called on
522n/a each line after it is sent. [default: None]
523n/a
524n/a Returns:
525n/a The response code.
526n/a """
527n/a self.voidcmd('TYPE A')
528n/a with self.transfercmd(cmd) as conn:
529n/a while 1:
530n/a buf = fp.readline(self.maxline + 1)
531n/a if len(buf) > self.maxline:
532n/a raise Error("got more than %d bytes" % self.maxline)
533n/a if not buf:
534n/a break
535n/a if buf[-2:] != B_CRLF:
536n/a if buf[-1] in B_CRLF: buf = buf[:-1]
537n/a buf = buf + B_CRLF
538n/a conn.sendall(buf)
539n/a if callback:
540n/a callback(buf)
541n/a # shutdown ssl layer
542n/a if _SSLSocket is not None and isinstance(conn, _SSLSocket):
543n/a conn.unwrap()
544n/a return self.voidresp()
545n/a
546n/a def acct(self, password):
547n/a '''Send new account name.'''
548n/a cmd = 'ACCT ' + password
549n/a return self.voidcmd(cmd)
550n/a
551n/a def nlst(self, *args):
552n/a '''Return a list of files in a given directory (default the current).'''
553n/a cmd = 'NLST'
554n/a for arg in args:
555n/a cmd = cmd + (' ' + arg)
556n/a files = []
557n/a self.retrlines(cmd, files.append)
558n/a return files
559n/a
560n/a def dir(self, *args):
561n/a '''List a directory in long form.
562n/a By default list current directory to stdout.
563n/a Optional last argument is callback function; all
564n/a non-empty arguments before it are concatenated to the
565n/a LIST command. (This *should* only be used for a pathname.)'''
566n/a cmd = 'LIST'
567n/a func = None
568n/a if args[-1:] and type(args[-1]) != type(''):
569n/a args, func = args[:-1], args[-1]
570n/a for arg in args:
571n/a if arg:
572n/a cmd = cmd + (' ' + arg)
573n/a self.retrlines(cmd, func)
574n/a
575n/a def mlsd(self, path="", facts=[]):
576n/a '''List a directory in a standardized format by using MLSD
577n/a command (RFC-3659). If path is omitted the current directory
578n/a is assumed. "facts" is a list of strings representing the type
579n/a of information desired (e.g. ["type", "size", "perm"]).
580n/a
581n/a Return a generator object yielding a tuple of two elements
582n/a for every file found in path.
583n/a First element is the file name, the second one is a dictionary
584n/a including a variable number of "facts" depending on the server
585n/a and whether "facts" argument has been provided.
586n/a '''
587n/a if facts:
588n/a self.sendcmd("OPTS MLST " + ";".join(facts) + ";")
589n/a if path:
590n/a cmd = "MLSD %s" % path
591n/a else:
592n/a cmd = "MLSD"
593n/a lines = []
594n/a self.retrlines(cmd, lines.append)
595n/a for line in lines:
596n/a facts_found, _, name = line.rstrip(CRLF).partition(' ')
597n/a entry = {}
598n/a for fact in facts_found[:-1].split(";"):
599n/a key, _, value = fact.partition("=")
600n/a entry[key.lower()] = value
601n/a yield (name, entry)
602n/a
603n/a def rename(self, fromname, toname):
604n/a '''Rename a file.'''
605n/a resp = self.sendcmd('RNFR ' + fromname)
606n/a if resp[0] != '3':
607n/a raise error_reply(resp)
608n/a return self.voidcmd('RNTO ' + toname)
609n/a
610n/a def delete(self, filename):
611n/a '''Delete a file.'''
612n/a resp = self.sendcmd('DELE ' + filename)
613n/a if resp[:3] in {'250', '200'}:
614n/a return resp
615n/a else:
616n/a raise error_reply(resp)
617n/a
618n/a def cwd(self, dirname):
619n/a '''Change to a directory.'''
620n/a if dirname == '..':
621n/a try:
622n/a return self.voidcmd('CDUP')
623n/a except error_perm as msg:
624n/a if msg.args[0][:3] != '500':
625n/a raise
626n/a elif dirname == '':
627n/a dirname = '.' # does nothing, but could return error
628n/a cmd = 'CWD ' + dirname
629n/a return self.voidcmd(cmd)
630n/a
631n/a def size(self, filename):
632n/a '''Retrieve the size of a file.'''
633n/a # The SIZE command is defined in RFC-3659
634n/a resp = self.sendcmd('SIZE ' + filename)
635n/a if resp[:3] == '213':
636n/a s = resp[3:].strip()
637n/a return int(s)
638n/a
639n/a def mkd(self, dirname):
640n/a '''Make a directory, return its full pathname.'''
641n/a resp = self.voidcmd('MKD ' + dirname)
642n/a # fix around non-compliant implementations such as IIS shipped
643n/a # with Windows server 2003
644n/a if not resp.startswith('257'):
645n/a return ''
646n/a return parse257(resp)
647n/a
648n/a def rmd(self, dirname):
649n/a '''Remove a directory.'''
650n/a return self.voidcmd('RMD ' + dirname)
651n/a
652n/a def pwd(self):
653n/a '''Return current working directory.'''
654n/a resp = self.voidcmd('PWD')
655n/a # fix around non-compliant implementations such as IIS shipped
656n/a # with Windows server 2003
657n/a if not resp.startswith('257'):
658n/a return ''
659n/a return parse257(resp)
660n/a
661n/a def quit(self):
662n/a '''Quit, and close the connection.'''
663n/a resp = self.voidcmd('QUIT')
664n/a self.close()
665n/a return resp
666n/a
667n/a def close(self):
668n/a '''Close the connection without assuming anything about it.'''
669n/a try:
670n/a file = self.file
671n/a self.file = None
672n/a if file is not None:
673n/a file.close()
674n/a finally:
675n/a sock = self.sock
676n/a self.sock = None
677n/a if sock is not None:
678n/a sock.close()
679n/a
680n/atry:
681n/a import ssl
682n/aexcept ImportError:
683n/a _SSLSocket = None
684n/aelse:
685n/a _SSLSocket = ssl.SSLSocket
686n/a
687n/a class FTP_TLS(FTP):
688n/a '''A FTP subclass which adds TLS support to FTP as described
689n/a in RFC-4217.
690n/a
691n/a Connect as usual to port 21 implicitly securing the FTP control
692n/a connection before authenticating.
693n/a
694n/a Securing the data connection requires user to explicitly ask
695n/a for it by calling prot_p() method.
696n/a
697n/a Usage example:
698n/a >>> from ftplib import FTP_TLS
699n/a >>> ftps = FTP_TLS('ftp.python.org')
700n/a >>> ftps.login() # login anonymously previously securing control channel
701n/a '230 Guest login ok, access restrictions apply.'
702n/a >>> ftps.prot_p() # switch to secure data connection
703n/a '200 Protection level set to P'
704n/a >>> ftps.retrlines('LIST') # list directory content securely
705n/a total 9
706n/a drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
707n/a drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
708n/a drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
709n/a drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
710n/a d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
711n/a drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
712n/a drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
713n/a drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
714n/a -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
715n/a '226 Transfer complete.'
716n/a >>> ftps.quit()
717n/a '221 Goodbye.'
718n/a >>>
719n/a '''
720n/a ssl_version = ssl.PROTOCOL_SSLv23
721n/a
722n/a def __init__(self, host='', user='', passwd='', acct='', keyfile=None,
723n/a certfile=None, context=None,
724n/a timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
725n/a if context is not None and keyfile is not None:
726n/a raise ValueError("context and keyfile arguments are mutually "
727n/a "exclusive")
728n/a if context is not None and certfile is not None:
729n/a raise ValueError("context and certfile arguments are mutually "
730n/a "exclusive")
731n/a if keyfile is not None or certfile is not None:
732n/a import warnings
733n/a warnings.warn("keyfile and certfile are deprecated, use a"
734n/a "custom context instead", DeprecationWarning, 2)
735n/a self.keyfile = keyfile
736n/a self.certfile = certfile
737n/a if context is None:
738n/a context = ssl._create_stdlib_context(self.ssl_version,
739n/a certfile=certfile,
740n/a keyfile=keyfile)
741n/a self.context = context
742n/a self._prot_p = False
743n/a FTP.__init__(self, host, user, passwd, acct, timeout, source_address)
744n/a
745n/a def login(self, user='', passwd='', acct='', secure=True):
746n/a if secure and not isinstance(self.sock, ssl.SSLSocket):
747n/a self.auth()
748n/a return FTP.login(self, user, passwd, acct)
749n/a
750n/a def auth(self):
751n/a '''Set up secure control connection by using TLS/SSL.'''
752n/a if isinstance(self.sock, ssl.SSLSocket):
753n/a raise ValueError("Already using TLS")
754n/a if self.ssl_version >= ssl.PROTOCOL_SSLv23:
755n/a resp = self.voidcmd('AUTH TLS')
756n/a else:
757n/a resp = self.voidcmd('AUTH SSL')
758n/a self.sock = self.context.wrap_socket(self.sock,
759n/a server_hostname=self.host)
760n/a self.file = self.sock.makefile(mode='r', encoding=self.encoding)
761n/a return resp
762n/a
763n/a def ccc(self):
764n/a '''Switch back to a clear-text control connection.'''
765n/a if not isinstance(self.sock, ssl.SSLSocket):
766n/a raise ValueError("not using TLS")
767n/a resp = self.voidcmd('CCC')
768n/a self.sock = self.sock.unwrap()
769n/a return resp
770n/a
771n/a def prot_p(self):
772n/a '''Set up secure data connection.'''
773n/a # PROT defines whether or not the data channel is to be protected.
774n/a # Though RFC-2228 defines four possible protection levels,
775n/a # RFC-4217 only recommends two, Clear and Private.
776n/a # Clear (PROT C) means that no security is to be used on the
777n/a # data-channel, Private (PROT P) means that the data-channel
778n/a # should be protected by TLS.
779n/a # PBSZ command MUST still be issued, but must have a parameter of
780n/a # '0' to indicate that no buffering is taking place and the data
781n/a # connection should not be encapsulated.
782n/a self.voidcmd('PBSZ 0')
783n/a resp = self.voidcmd('PROT P')
784n/a self._prot_p = True
785n/a return resp
786n/a
787n/a def prot_c(self):
788n/a '''Set up clear text data connection.'''
789n/a resp = self.voidcmd('PROT C')
790n/a self._prot_p = False
791n/a return resp
792n/a
793n/a # --- Overridden FTP methods
794n/a
795n/a def ntransfercmd(self, cmd, rest=None):
796n/a conn, size = FTP.ntransfercmd(self, cmd, rest)
797n/a if self._prot_p:
798n/a conn = self.context.wrap_socket(conn,
799n/a server_hostname=self.host)
800n/a return conn, size
801n/a
802n/a def abort(self):
803n/a # overridden as we can't pass MSG_OOB flag to sendall()
804n/a line = b'ABOR' + B_CRLF
805n/a self.sock.sendall(line)
806n/a resp = self.getmultiline()
807n/a if resp[:3] not in {'426', '225', '226'}:
808n/a raise error_proto(resp)
809n/a return resp
810n/a
811n/a __all__.append('FTP_TLS')
812n/a all_errors = (Error, OSError, EOFError, ssl.SSLError)
813n/a
814n/a
815n/a_150_re = None
816n/a
817n/adef parse150(resp):
818n/a '''Parse the '150' response for a RETR request.
819n/a Returns the expected transfer size or None; size is not guaranteed to
820n/a be present in the 150 message.
821n/a '''
822n/a if resp[:3] != '150':
823n/a raise error_reply(resp)
824n/a global _150_re
825n/a if _150_re is None:
826n/a import re
827n/a _150_re = re.compile(
828n/a r"150 .* \((\d+) bytes\)", re.IGNORECASE | re.ASCII)
829n/a m = _150_re.match(resp)
830n/a if not m:
831n/a return None
832n/a return int(m.group(1))
833n/a
834n/a
835n/a_227_re = None
836n/a
837n/adef parse227(resp):
838n/a '''Parse the '227' response for a PASV request.
839n/a Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
840n/a Return ('host.addr.as.numbers', port#) tuple.'''
841n/a
842n/a if resp[:3] != '227':
843n/a raise error_reply(resp)
844n/a global _227_re
845n/a if _227_re is None:
846n/a import re
847n/a _227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)', re.ASCII)
848n/a m = _227_re.search(resp)
849n/a if not m:
850n/a raise error_proto(resp)
851n/a numbers = m.groups()
852n/a host = '.'.join(numbers[:4])
853n/a port = (int(numbers[4]) << 8) + int(numbers[5])
854n/a return host, port
855n/a
856n/a
857n/adef parse229(resp, peer):
858n/a '''Parse the '229' response for an EPSV request.
859n/a Raises error_proto if it does not contain '(|||port|)'
860n/a Return ('host.addr.as.numbers', port#) tuple.'''
861n/a
862n/a if resp[:3] != '229':
863n/a raise error_reply(resp)
864n/a left = resp.find('(')
865n/a if left < 0: raise error_proto(resp)
866n/a right = resp.find(')', left + 1)
867n/a if right < 0:
868n/a raise error_proto(resp) # should contain '(|||port|)'
869n/a if resp[left + 1] != resp[right - 1]:
870n/a raise error_proto(resp)
871n/a parts = resp[left + 1:right].split(resp[left+1])
872n/a if len(parts) != 5:
873n/a raise error_proto(resp)
874n/a host = peer[0]
875n/a port = int(parts[3])
876n/a return host, port
877n/a
878n/a
879n/adef parse257(resp):
880n/a '''Parse the '257' response for a MKD or PWD request.
881n/a This is a response to a MKD or PWD request: a directory name.
882n/a Returns the directoryname in the 257 reply.'''
883n/a
884n/a if resp[:3] != '257':
885n/a raise error_reply(resp)
886n/a if resp[3:5] != ' "':
887n/a return '' # Not compliant to RFC 959, but UNIX ftpd does this
888n/a dirname = ''
889n/a i = 5
890n/a n = len(resp)
891n/a while i < n:
892n/a c = resp[i]
893n/a i = i+1
894n/a if c == '"':
895n/a if i >= n or resp[i] != '"':
896n/a break
897n/a i = i+1
898n/a dirname = dirname + c
899n/a return dirname
900n/a
901n/a
902n/adef print_line(line):
903n/a '''Default retrlines callback to print a line.'''
904n/a print(line)
905n/a
906n/a
907n/adef ftpcp(source, sourcename, target, targetname = '', type = 'I'):
908n/a '''Copy file from one FTP-instance to another.'''
909n/a if not targetname:
910n/a targetname = sourcename
911n/a type = 'TYPE ' + type
912n/a source.voidcmd(type)
913n/a target.voidcmd(type)
914n/a sourcehost, sourceport = parse227(source.sendcmd('PASV'))
915n/a target.sendport(sourcehost, sourceport)
916n/a # RFC 959: the user must "listen" [...] BEFORE sending the
917n/a # transfer request.
918n/a # So: STOR before RETR, because here the target is a "user".
919n/a treply = target.sendcmd('STOR ' + targetname)
920n/a if treply[:3] not in {'125', '150'}:
921n/a raise error_proto # RFC 959
922n/a sreply = source.sendcmd('RETR ' + sourcename)
923n/a if sreply[:3] not in {'125', '150'}:
924n/a raise error_proto # RFC 959
925n/a source.voidresp()
926n/a target.voidresp()
927n/a
928n/a
929n/adef test():
930n/a '''Test program.
931n/a Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
932n/a
933n/a -d dir
934n/a -l list
935n/a -p password
936n/a '''
937n/a
938n/a if len(sys.argv) < 2:
939n/a print(test.__doc__)
940n/a sys.exit(0)
941n/a
942n/a import netrc
943n/a
944n/a debugging = 0
945n/a rcfile = None
946n/a while sys.argv[1] == '-d':
947n/a debugging = debugging+1
948n/a del sys.argv[1]
949n/a if sys.argv[1][:2] == '-r':
950n/a # get name of alternate ~/.netrc file:
951n/a rcfile = sys.argv[1][2:]
952n/a del sys.argv[1]
953n/a host = sys.argv[1]
954n/a ftp = FTP(host)
955n/a ftp.set_debuglevel(debugging)
956n/a userid = passwd = acct = ''
957n/a try:
958n/a netrcobj = netrc.netrc(rcfile)
959n/a except OSError:
960n/a if rcfile is not None:
961n/a sys.stderr.write("Could not open account file"
962n/a " -- using anonymous login.")
963n/a else:
964n/a try:
965n/a userid, acct, passwd = netrcobj.authenticators(host)
966n/a except KeyError:
967n/a # no account for host
968n/a sys.stderr.write(
969n/a "No account -- using anonymous login.")
970n/a ftp.login(userid, passwd, acct)
971n/a for file in sys.argv[2:]:
972n/a if file[:2] == '-l':
973n/a ftp.dir(file[2:])
974n/a elif file[:2] == '-d':
975n/a cmd = 'CWD'
976n/a if file[2:]: cmd = cmd + ' ' + file[2:]
977n/a resp = ftp.sendcmd(cmd)
978n/a elif file == '-p':
979n/a ftp.set_pasv(not ftp.passiveserver)
980n/a else:
981n/a ftp.retrbinary('RETR ' + file, \
982n/a sys.stdout.write, 1024)
983n/a ftp.quit()
984n/a
985n/a
986n/aif __name__ == '__main__':
987n/a test()