PageRenderTime 40ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/ftplib.py

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