ftplib.py 35 KB

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