ftplib.py 35 KB

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