ftplib.py 34 KB

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