ftplib.py 34 KB

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