ftplib.py 34 KB

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