ftplib.py 34 KB

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