/Lib/ftplib.py

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