ftplib.py 37 KB

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