PageRenderTime 46ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/ftplib.py

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