ftplib.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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 data := conn.recv(blocksize):
  387. callback(data)
  388. # shutdown ssl layer
  389. if _SSLSocket is not None and isinstance(conn, _SSLSocket):
  390. conn.unwrap()
  391. return self.voidresp()
  392. def retrlines(self, cmd, callback = None):
  393. """Retrieve data in line mode. A new port is created for you.
  394. Args:
  395. cmd: A RETR, LIST, or NLST command.
  396. callback: An optional single parameter callable that is called
  397. for each line with the trailing CRLF stripped.
  398. [default: print_line()]
  399. Returns:
  400. The response code.
  401. """
  402. if callback is None:
  403. callback = print_line
  404. resp = self.sendcmd('TYPE A')
  405. with self.transfercmd(cmd) as conn, \
  406. conn.makefile('r', encoding=self.encoding) as fp:
  407. while 1:
  408. line = fp.readline(self.maxline + 1)
  409. if len(line) > self.maxline:
  410. raise Error("got more than %d bytes" % self.maxline)
  411. if self.debugging > 2:
  412. print('*retr*', repr(line))
  413. if not line:
  414. break
  415. if line[-2:] == CRLF:
  416. line = line[:-2]
  417. elif line[-1:] == '\n':
  418. line = line[:-1]
  419. callback(line)
  420. # shutdown ssl layer
  421. if _SSLSocket is not None and isinstance(conn, _SSLSocket):
  422. conn.unwrap()
  423. return self.voidresp()
  424. def storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None):
  425. """Store a file in binary mode. A new port is created for you.
  426. Args:
  427. cmd: A STOR command.
  428. fp: A file-like object with a read(num_bytes) method.
  429. blocksize: The maximum data size to read from fp and send over
  430. the connection at once. [default: 8192]
  431. callback: An optional single parameter callable that is called on
  432. each block of data after it is sent. [default: None]
  433. rest: Passed to transfercmd(). [default: None]
  434. Returns:
  435. The response code.
  436. """
  437. self.voidcmd('TYPE I')
  438. with self.transfercmd(cmd, rest) as conn:
  439. while buf := fp.read(blocksize):
  440. conn.sendall(buf)
  441. if callback:
  442. callback(buf)
  443. # shutdown ssl layer
  444. if _SSLSocket is not None and isinstance(conn, _SSLSocket):
  445. conn.unwrap()
  446. return self.voidresp()
  447. def storlines(self, cmd, fp, callback=None):
  448. """Store a file in line mode. A new port is created for you.
  449. Args:
  450. cmd: A STOR command.
  451. fp: A file-like object with a readline() method.
  452. callback: An optional single parameter callable that is called on
  453. each line after it is sent. [default: None]
  454. Returns:
  455. The response code.
  456. """
  457. self.voidcmd('TYPE A')
  458. with self.transfercmd(cmd) as conn:
  459. while 1:
  460. buf = fp.readline(self.maxline + 1)
  461. if len(buf) > self.maxline:
  462. raise Error("got more than %d bytes" % self.maxline)
  463. if not buf:
  464. break
  465. if buf[-2:] != B_CRLF:
  466. if buf[-1] in B_CRLF: buf = buf[:-1]
  467. buf = buf + B_CRLF
  468. conn.sendall(buf)
  469. if callback:
  470. callback(buf)
  471. # shutdown ssl layer
  472. if _SSLSocket is not None and isinstance(conn, _SSLSocket):
  473. conn.unwrap()
  474. return self.voidresp()
  475. def acct(self, password):
  476. '''Send new account name.'''
  477. cmd = 'ACCT ' + password
  478. return self.voidcmd(cmd)
  479. def nlst(self, *args):
  480. '''Return a list of files in a given directory (default the current).'''
  481. cmd = 'NLST'
  482. for arg in args:
  483. cmd = cmd + (' ' + arg)
  484. files = []
  485. self.retrlines(cmd, files.append)
  486. return files
  487. def dir(self, *args):
  488. '''List a directory in long form.
  489. By default list current directory to stdout.
  490. Optional last argument is callback function; all
  491. non-empty arguments before it are concatenated to the
  492. LIST command. (This *should* only be used for a pathname.)'''
  493. cmd = 'LIST'
  494. func = None
  495. if args[-1:] and not isinstance(args[-1], str):
  496. args, func = args[:-1], args[-1]
  497. for arg in args:
  498. if arg:
  499. cmd = cmd + (' ' + arg)
  500. self.retrlines(cmd, func)
  501. def mlsd(self, path="", facts=[]):
  502. '''List a directory in a standardized format by using MLSD
  503. command (RFC-3659). If path is omitted the current directory
  504. is assumed. "facts" is a list of strings representing the type
  505. of information desired (e.g. ["type", "size", "perm"]).
  506. Return a generator object yielding a tuple of two elements
  507. for every file found in path.
  508. First element is the file name, the second one is a dictionary
  509. including a variable number of "facts" depending on the server
  510. and whether "facts" argument has been provided.
  511. '''
  512. if facts:
  513. self.sendcmd("OPTS MLST " + ";".join(facts) + ";")
  514. if path:
  515. cmd = "MLSD %s" % path
  516. else:
  517. cmd = "MLSD"
  518. lines = []
  519. self.retrlines(cmd, lines.append)
  520. for line in lines:
  521. facts_found, _, name = line.rstrip(CRLF).partition(' ')
  522. entry = {}
  523. for fact in facts_found[:-1].split(";"):
  524. key, _, value = fact.partition("=")
  525. entry[key.lower()] = value
  526. yield (name, entry)
  527. def rename(self, fromname, toname):
  528. '''Rename a file.'''
  529. resp = self.sendcmd('RNFR ' + fromname)
  530. if resp[0] != '3':
  531. raise error_reply(resp)
  532. return self.voidcmd('RNTO ' + toname)
  533. def delete(self, filename):
  534. '''Delete a file.'''
  535. resp = self.sendcmd('DELE ' + filename)
  536. if resp[:3] in {'250', '200'}:
  537. return resp
  538. else:
  539. raise error_reply(resp)
  540. def cwd(self, dirname):
  541. '''Change to a directory.'''
  542. if dirname == '..':
  543. try:
  544. return self.voidcmd('CDUP')
  545. except error_perm as msg:
  546. if msg.args[0][:3] != '500':
  547. raise
  548. elif dirname == '':
  549. dirname = '.' # does nothing, but could return error
  550. cmd = 'CWD ' + dirname
  551. return self.voidcmd(cmd)
  552. def size(self, filename):
  553. '''Retrieve the size of a file.'''
  554. # The SIZE command is defined in RFC-3659
  555. resp = self.sendcmd('SIZE ' + filename)
  556. if resp[:3] == '213':
  557. s = resp[3:].strip()
  558. return int(s)
  559. def mkd(self, dirname):
  560. '''Make a directory, return its full pathname.'''
  561. resp = self.voidcmd('MKD ' + dirname)
  562. # fix around non-compliant implementations such as IIS shipped
  563. # with Windows server 2003
  564. if not resp.startswith('257'):
  565. return ''
  566. return parse257(resp)
  567. def rmd(self, dirname):
  568. '''Remove a directory.'''
  569. return self.voidcmd('RMD ' + dirname)
  570. def pwd(self):
  571. '''Return current working directory.'''
  572. resp = self.voidcmd('PWD')
  573. # fix around non-compliant implementations such as IIS shipped
  574. # with Windows server 2003
  575. if not resp.startswith('257'):
  576. return ''
  577. return parse257(resp)
  578. def quit(self):
  579. '''Quit, and close the connection.'''
  580. resp = self.voidcmd('QUIT')
  581. self.close()
  582. return resp
  583. def close(self):
  584. '''Close the connection without assuming anything about it.'''
  585. try:
  586. file = self.file
  587. self.file = None
  588. if file is not None:
  589. file.close()
  590. finally:
  591. sock = self.sock
  592. self.sock = None
  593. if sock is not None:
  594. sock.close()
  595. try:
  596. import ssl
  597. except ImportError:
  598. _SSLSocket = None
  599. else:
  600. _SSLSocket = ssl.SSLSocket
  601. class FTP_TLS(FTP):
  602. '''A FTP subclass which adds TLS support to FTP as described
  603. in RFC-4217.
  604. Connect as usual to port 21 implicitly securing the FTP control
  605. connection before authenticating.
  606. Securing the data connection requires user to explicitly ask
  607. for it by calling prot_p() method.
  608. Usage example:
  609. >>> from ftplib import FTP_TLS
  610. >>> ftps = FTP_TLS('ftp.python.org')
  611. >>> ftps.login() # login anonymously previously securing control channel
  612. '230 Guest login ok, access restrictions apply.'
  613. >>> ftps.prot_p() # switch to secure data connection
  614. '200 Protection level set to P'
  615. >>> ftps.retrlines('LIST') # list directory content securely
  616. total 9
  617. drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
  618. drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
  619. drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
  620. drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
  621. d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
  622. drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
  623. drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
  624. drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
  625. -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
  626. '226 Transfer complete.'
  627. >>> ftps.quit()
  628. '221 Goodbye.'
  629. >>>
  630. '''
  631. def __init__(self, host='', user='', passwd='', acct='',
  632. *, context=None, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  633. source_address=None, encoding='utf-8'):
  634. if context is None:
  635. context = ssl._create_stdlib_context()
  636. self.context = context
  637. self._prot_p = False
  638. super().__init__(host, user, passwd, acct,
  639. timeout, source_address, encoding=encoding)
  640. def login(self, user='', passwd='', acct='', secure=True):
  641. if secure and not isinstance(self.sock, ssl.SSLSocket):
  642. self.auth()
  643. return super().login(user, passwd, acct)
  644. def auth(self):
  645. '''Set up secure control connection by using TLS/SSL.'''
  646. if isinstance(self.sock, ssl.SSLSocket):
  647. raise ValueError("Already using TLS")
  648. if self.context.protocol >= ssl.PROTOCOL_TLS:
  649. resp = self.voidcmd('AUTH TLS')
  650. else:
  651. resp = self.voidcmd('AUTH SSL')
  652. self.sock = self.context.wrap_socket(self.sock, server_hostname=self.host)
  653. self.file = self.sock.makefile(mode='r', encoding=self.encoding)
  654. return resp
  655. def ccc(self):
  656. '''Switch back to a clear-text control connection.'''
  657. if not isinstance(self.sock, ssl.SSLSocket):
  658. raise ValueError("not using TLS")
  659. resp = self.voidcmd('CCC')
  660. self.sock = self.sock.unwrap()
  661. return resp
  662. def prot_p(self):
  663. '''Set up secure data connection.'''
  664. # PROT defines whether or not the data channel is to be protected.
  665. # Though RFC-2228 defines four possible protection levels,
  666. # RFC-4217 only recommends two, Clear and Private.
  667. # Clear (PROT C) means that no security is to be used on the
  668. # data-channel, Private (PROT P) means that the data-channel
  669. # should be protected by TLS.
  670. # PBSZ command MUST still be issued, but must have a parameter of
  671. # '0' to indicate that no buffering is taking place and the data
  672. # connection should not be encapsulated.
  673. self.voidcmd('PBSZ 0')
  674. resp = self.voidcmd('PROT P')
  675. self._prot_p = True
  676. return resp
  677. def prot_c(self):
  678. '''Set up clear text data connection.'''
  679. resp = self.voidcmd('PROT C')
  680. self._prot_p = False
  681. return resp
  682. # --- Overridden FTP methods
  683. def ntransfercmd(self, cmd, rest=None):
  684. conn, size = super().ntransfercmd(cmd, rest)
  685. if self._prot_p:
  686. conn = self.context.wrap_socket(conn,
  687. server_hostname=self.host)
  688. return conn, size
  689. def abort(self):
  690. # overridden as we can't pass MSG_OOB flag to sendall()
  691. line = b'ABOR' + B_CRLF
  692. self.sock.sendall(line)
  693. resp = self.getmultiline()
  694. if resp[:3] not in {'426', '225', '226'}:
  695. raise error_proto(resp)
  696. return resp
  697. __all__.append('FTP_TLS')
  698. all_errors = (Error, OSError, EOFError, ssl.SSLError)
  699. _150_re = None
  700. def parse150(resp):
  701. '''Parse the '150' response for a RETR request.
  702. Returns the expected transfer size or None; size is not guaranteed to
  703. be present in the 150 message.
  704. '''
  705. if resp[:3] != '150':
  706. raise error_reply(resp)
  707. global _150_re
  708. if _150_re is None:
  709. import re
  710. _150_re = re.compile(
  711. r"150 .* \((\d+) bytes\)", re.IGNORECASE | re.ASCII)
  712. m = _150_re.match(resp)
  713. if not m:
  714. return None
  715. return int(m.group(1))
  716. _227_re = None
  717. def parse227(resp):
  718. '''Parse the '227' response for a PASV request.
  719. Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
  720. Return ('host.addr.as.numbers', port#) tuple.'''
  721. if resp[:3] != '227':
  722. raise error_reply(resp)
  723. global _227_re
  724. if _227_re is None:
  725. import re
  726. _227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)', re.ASCII)
  727. m = _227_re.search(resp)
  728. if not m:
  729. raise error_proto(resp)
  730. numbers = m.groups()
  731. host = '.'.join(numbers[:4])
  732. port = (int(numbers[4]) << 8) + int(numbers[5])
  733. return host, port
  734. def parse229(resp, peer):
  735. '''Parse the '229' response for an EPSV request.
  736. Raises error_proto if it does not contain '(|||port|)'
  737. Return ('host.addr.as.numbers', port#) tuple.'''
  738. if resp[:3] != '229':
  739. raise error_reply(resp)
  740. left = resp.find('(')
  741. if left < 0: raise error_proto(resp)
  742. right = resp.find(')', left + 1)
  743. if right < 0:
  744. raise error_proto(resp) # should contain '(|||port|)'
  745. if resp[left + 1] != resp[right - 1]:
  746. raise error_proto(resp)
  747. parts = resp[left + 1:right].split(resp[left+1])
  748. if len(parts) != 5:
  749. raise error_proto(resp)
  750. host = peer[0]
  751. port = int(parts[3])
  752. return host, port
  753. def parse257(resp):
  754. '''Parse the '257' response for a MKD or PWD request.
  755. This is a response to a MKD or PWD request: a directory name.
  756. Returns the directoryname in the 257 reply.'''
  757. if resp[:3] != '257':
  758. raise error_reply(resp)
  759. if resp[3:5] != ' "':
  760. return '' # Not compliant to RFC 959, but UNIX ftpd does this
  761. dirname = ''
  762. i = 5
  763. n = len(resp)
  764. while i < n:
  765. c = resp[i]
  766. i = i+1
  767. if c == '"':
  768. if i >= n or resp[i] != '"':
  769. break
  770. i = i+1
  771. dirname = dirname + c
  772. return dirname
  773. def print_line(line):
  774. '''Default retrlines callback to print a line.'''
  775. print(line)
  776. def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
  777. '''Copy file from one FTP-instance to another.'''
  778. if not targetname:
  779. targetname = sourcename
  780. type = 'TYPE ' + type
  781. source.voidcmd(type)
  782. target.voidcmd(type)
  783. sourcehost, sourceport = parse227(source.sendcmd('PASV'))
  784. target.sendport(sourcehost, sourceport)
  785. # RFC 959: the user must "listen" [...] BEFORE sending the
  786. # transfer request.
  787. # So: STOR before RETR, because here the target is a "user".
  788. treply = target.sendcmd('STOR ' + targetname)
  789. if treply[:3] not in {'125', '150'}:
  790. raise error_proto # RFC 959
  791. sreply = source.sendcmd('RETR ' + sourcename)
  792. if sreply[:3] not in {'125', '150'}:
  793. raise error_proto # RFC 959
  794. source.voidresp()
  795. target.voidresp()
  796. def test():
  797. '''Test program.
  798. Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
  799. -d dir
  800. -l list
  801. -p password
  802. '''
  803. if len(sys.argv) < 2:
  804. print(test.__doc__)
  805. sys.exit(0)
  806. import netrc
  807. debugging = 0
  808. rcfile = None
  809. while sys.argv[1] == '-d':
  810. debugging = debugging+1
  811. del sys.argv[1]
  812. if sys.argv[1][:2] == '-r':
  813. # get name of alternate ~/.netrc file:
  814. rcfile = sys.argv[1][2:]
  815. del sys.argv[1]
  816. host = sys.argv[1]
  817. ftp = FTP(host)
  818. ftp.set_debuglevel(debugging)
  819. userid = passwd = acct = ''
  820. try:
  821. netrcobj = netrc.netrc(rcfile)
  822. except OSError:
  823. if rcfile is not None:
  824. sys.stderr.write("Could not open account file"
  825. " -- using anonymous login.")
  826. else:
  827. try:
  828. userid, acct, passwd = netrcobj.authenticators(host)
  829. except KeyError:
  830. # no account for host
  831. sys.stderr.write(
  832. "No account -- using anonymous login.")
  833. ftp.login(userid, passwd, acct)
  834. for file in sys.argv[2:]:
  835. if file[:2] == '-l':
  836. ftp.dir(file[2:])
  837. elif file[:2] == '-d':
  838. cmd = 'CWD'
  839. if file[2:]: cmd = cmd + ' ' + file[2:]
  840. resp = ftp.sendcmd(cmd)
  841. elif file == '-p':
  842. ftp.set_pasv(not ftp.passiveserver)
  843. else:
  844. ftp.retrbinary('RETR ' + file, \
  845. sys.stdout.write, 1024)
  846. ftp.quit()
  847. if __name__ == '__main__':
  848. test()