You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ftplib.py 25KB

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