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.

1715 lines
68 KiB

  1. From: Bryan Quigley <bryan.quigley@canonical.com>
  2. Date: Sat, 2 Nov 2019 21:06:44 -0700
  3. Subject: Python3 port of ndiff
  4. Ported all python scrips in ndiff/ except setup.py
  5. Some hints on cmp taken from #1484
  6. Minor tweaks to Makefile to support python3, but unsure if
  7. there is a better way to do that.
  8. Seperated .travis.yml commands for easier debugging where it breaks.
  9. This closes the easy half of #1176
  10. Resolves: #1484
  11. ---
  12. .travis.yml | 8 +-
  13. Makefile.in | 6 +-
  14. ndiff/ndiff.py | 495 +++++++++++++++++++++---------------------
  15. ndiff/ndifftest.py | 94 ++++----
  16. ndiff/scripts/ndiff | 14 +-
  17. ndiff/setup.py | 34 +--
  18. ndiff/test-scans/anonymize.py | 18 +-
  19. 7 files changed, 337 insertions(+), 332 deletions(-)
  20. mode change 100644 => 100755 ndiff/setup.py
  21. diff --git a/.travis.yml b/.travis.yml
  22. index 145ebc6..9bb50d6 100644
  23. --- a/.travis.yml
  24. +++ b/.travis.yml
  25. @@ -4,7 +4,13 @@ compiler:
  26. - clang
  27. # Change this to your needs
  28. sudo: false
  29. -script: mkdir /tmp/n && ./configure $SSL_FLAG $LUA_FLAG --prefix=/tmp/n && make && make check && make install && /tmp/n/bin/nmap -A localhost
  30. +script:
  31. + - "mkdir /tmp/n"
  32. + - "./configure $SSL_FLAG $LUA_FLAG --prefix=/tmp/n"
  33. + - "make"
  34. + - "make check"
  35. + - "make install"
  36. + - "/tmp/n/bin/nmap -A localhost"
  37. env:
  38. - SSL_FLAG="--without-openssl" LUA_FLAG="--without-liblua"
  39. diff --git a/Makefile.in b/Makefile.in
  40. index 7ac5ae5..a0152f4 100644
  41. --- a/Makefile.in
  42. +++ b/Makefile.in
  43. @@ -35,6 +35,7 @@ ZENMAPDIR = @ZENMAPDIR@
  44. NDIFFDIR = @NDIFFDIR@
  45. NPINGDIR = @NPINGDIR@
  46. PYTHON = @PYTHON@
  47. +PYTHON3 = /usr/bin/env python3
  48. DEFS = @DEFS@ -DNMAP_PLATFORM=\"$(NMAP_PLATFORM)\" -DNMAPDATADIR=\"$(nmapdatadir)\"
  49. # With GCC, add extra security checks to source code.
  50. # http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
  51. @@ -368,6 +369,7 @@ tests/check_dns: $(OBJS)
  52. # this as the location of the interpreter whenever we're not doing a
  53. # local installation.
  54. DEFAULT_PYTHON_PATH = /usr/bin/env python
  55. +DEFAULT_PYTHON3_PATH = /usr/bin/env python3
  56. build-zenmap: $(ZENMAPDIR)/setup.py $(ZENMAPDIR)/zenmapCore/Version.py
  57. # When DESTDIR is defined, assume we're building an executable
  58. @@ -388,7 +390,7 @@ install-zenmap: $(ZENMAPDIR)/setup.py
  59. ln -sf zenmap $(DESTDIR)$(bindir)/xnmap
  60. build-ndiff:
  61. - cd $(NDIFFDIR) && $(PYTHON) setup.py build $(if $(DESTDIR),--executable "$(DEFAULT_PYTHON_PATH)")
  62. + cd $(NDIFFDIR) && $(PYTHON) setup.py build $(if $(DESTDIR),--executable "$(DEFAULT_PYTHON3_PATH)")
  63. build-nping: $(NPINGDIR)/Makefile build-nbase build-nsock build-netutil $(NPINGDIR)/nping.h @DNET_BUILD@ @PCAP_BUILD@
  64. @cd $(NPINGDIR) && $(MAKE)
  65. @@ -458,7 +460,7 @@ check-ncat:
  66. @cd $(NCATDIR) && $(MAKE) check
  67. check-ndiff:
  68. - @cd $(NDIFFDIR) && $(PYTHON) ndifftest.py
  69. + @cd $(NDIFFDIR) && $(PYTHON3) ndifftest.py
  70. check-nsock:
  71. @cd $(NSOCKDIR)/src && $(MAKE) check
  72. diff --git a/ndiff/ndiff.py b/ndiff/ndiff.py
  73. index 043273f..abbd1c5 100755
  74. --- a/ndiff/ndiff.py
  75. +++ b/ndiff/ndiff.py
  76. @@ -1,4 +1,4 @@
  77. -#!/usr/bin/env python
  78. +#!/usr/bin/env python3
  79. # Ndiff
  80. #
  81. @@ -26,11 +26,11 @@ xml.__path__ = [x for x in xml.__path__ if "_xmlplus" not in x]
  82. import xml.sax
  83. import xml.sax.saxutils
  84. import xml.dom.minidom
  85. -from StringIO import StringIO
  86. +from io import StringIO
  87. verbose = False
  88. -NDIFF_XML_VERSION = u"1"
  89. +NDIFF_XML_VERSION = "1"
  90. class OverrideEntityResolver(xml.sax.handler.EntityResolver):
  91. @@ -78,35 +78,35 @@ class Scan(object):
  92. def write_nmaprun_open(self, writer):
  93. attrs = {}
  94. if self.scanner is not None:
  95. - attrs[u"scanner"] = self.scanner
  96. + attrs["scanner"] = self.scanner
  97. if self.args is not None:
  98. - attrs[u"args"] = self.args
  99. + attrs["args"] = self.args
  100. if self.start_date is not None:
  101. - attrs[u"start"] = "%d" % time.mktime(self.start_date.timetuple())
  102. - attrs[u"startstr"] = self.start_date.strftime(
  103. + attrs["start"] = "%d" % time.mktime(self.start_date.timetuple())
  104. + attrs["startstr"] = self.start_date.strftime(
  105. "%a %b %d %H:%M:%S %Y")
  106. if self.version is not None:
  107. - attrs[u"version"] = self.version
  108. - writer.startElement(u"nmaprun", attrs)
  109. + attrs["version"] = self.version
  110. + writer.startElement("nmaprun", attrs)
  111. def write_nmaprun_close(self, writer):
  112. - writer.endElement(u"nmaprun")
  113. + writer.endElement("nmaprun")
  114. def nmaprun_to_dom_fragment(self, document):
  115. frag = document.createDocumentFragment()
  116. - elem = document.createElement(u"nmaprun")
  117. + elem = document.createElement("nmaprun")
  118. if self.scanner is not None:
  119. - elem.setAttribute(u"scanner", self.scanner)
  120. + elem.setAttribute("scanner", self.scanner)
  121. if self.args is not None:
  122. - elem.setAttribute(u"args", self.args)
  123. + elem.setAttribute("args", self.args)
  124. if self.start_date is not None:
  125. elem.setAttribute(
  126. - u"start", "%d" % time.mktime(self.start_date.timetuple()))
  127. + "start", "%d" % time.mktime(self.start_date.timetuple()))
  128. elem.setAttribute(
  129. - u"startstr",
  130. + "startstr",
  131. self.start_date.strftime("%a %b %d %H:%M:%S %Y"))
  132. if self.version is not None:
  133. - elem.setAttribute(u"version", self.version)
  134. + elem.setAttribute("version", self.version)
  135. frag.appendChild(elem)
  136. return frag
  137. @@ -136,17 +136,17 @@ class Host(object):
  138. def format_name(self):
  139. """Return a human-readable identifier for this host."""
  140. - address_s = u", ".join(a.s for a in sorted(self.addresses))
  141. - hostname_s = u", ".join(sorted(self.hostnames))
  142. + address_s = ", ".join(a.s for a in sorted(self.addresses))
  143. + hostname_s = ", ".join(sorted(self.hostnames))
  144. if len(hostname_s) > 0:
  145. if len(address_s) > 0:
  146. - return u"%s (%s)" % (hostname_s, address_s)
  147. + return "%s (%s)" % (hostname_s, address_s)
  148. else:
  149. return hostname_s
  150. elif len(address_s) > 0:
  151. return address_s
  152. else:
  153. - return u"<no name>"
  154. + return "<no name>"
  155. def add_port(self, port):
  156. self.ports[port.spec] = port
  157. @@ -163,46 +163,46 @@ class Host(object):
  158. return state is None or state in self.extraports
  159. def extraports_string(self):
  160. - list = [(count, state) for (state, count) in self.extraports.items()]
  161. + locallist = [(count, state) for (state, count) in list(self.extraports.items())]
  162. # Reverse-sort by count.
  163. - list.sort(reverse=True)
  164. - return u", ".join(
  165. - [u"%d %s ports" % (count, state) for (count, state) in list])
  166. + locallist.sort(reverse=True)
  167. + return ", ".join(
  168. + ["%d %s ports" % (count, state) for (count, state) in locallist])
  169. def state_to_dom_fragment(self, document):
  170. frag = document.createDocumentFragment()
  171. if self.state is not None:
  172. - elem = document.createElement(u"status")
  173. - elem.setAttribute(u"state", self.state)
  174. + elem = document.createElement("status")
  175. + elem.setAttribute("state", self.state)
  176. frag.appendChild(elem)
  177. return frag
  178. def hostname_to_dom_fragment(self, document, hostname):
  179. frag = document.createDocumentFragment()
  180. - elem = document.createElement(u"hostname")
  181. - elem.setAttribute(u"name", hostname)
  182. + elem = document.createElement("hostname")
  183. + elem.setAttribute("name", hostname)
  184. frag.appendChild(elem)
  185. return frag
  186. def extraports_to_dom_fragment(self, document):
  187. frag = document.createDocumentFragment()
  188. - for state, count in self.extraports.items():
  189. - elem = document.createElement(u"extraports")
  190. - elem.setAttribute(u"state", state)
  191. - elem.setAttribute(u"count", unicode(count))
  192. + for state, count in list(self.extraports.items()):
  193. + elem = document.createElement("extraports")
  194. + elem.setAttribute("state", state)
  195. + elem.setAttribute("count", str(count))
  196. frag.appendChild(elem)
  197. return frag
  198. def os_to_dom_fragment(self, document, os):
  199. frag = document.createDocumentFragment()
  200. - elem = document.createElement(u"osmatch")
  201. - elem.setAttribute(u"name", os)
  202. + elem = document.createElement("osmatch")
  203. + elem.setAttribute("name", os)
  204. frag.appendChild(elem)
  205. return frag
  206. def to_dom_fragment(self, document):
  207. frag = document.createDocumentFragment()
  208. - elem = document.createElement(u"host")
  209. + elem = document.createElement("host")
  210. if self.state is not None:
  211. elem.appendChild(self.state_to_dom_fragment(document))
  212. @@ -211,13 +211,13 @@ class Host(object):
  213. elem.appendChild(addr.to_dom_fragment(document))
  214. if len(self.hostnames) > 0:
  215. - hostnames_elem = document.createElement(u"hostnames")
  216. + hostnames_elem = document.createElement("hostnames")
  217. for hostname in self.hostnames:
  218. hostnames_elem.appendChild(
  219. self.hostname_to_dom_fragment(document, hostname))
  220. elem.appendChild(hostnames_elem)
  221. - ports_elem = document.createElement(u"ports")
  222. + ports_elem = document.createElement("ports")
  223. ports_elem.appendChild(self.extraports_to_dom_fragment(document))
  224. for port in sorted(self.ports.values()):
  225. if not self.is_extraports(port.state):
  226. @@ -226,13 +226,13 @@ class Host(object):
  227. elem.appendChild(ports_elem)
  228. if len(self.os) > 0:
  229. - os_elem = document.createElement(u"os")
  230. + os_elem = document.createElement("os")
  231. for os in self.os:
  232. os_elem.appendChild(self.os_to_dom_fragment(document, os))
  233. elem.appendChild(os_elem)
  234. if len(self.script_results) > 0:
  235. - hostscript_elem = document.createElement(u"hostscript")
  236. + hostscript_elem = document.createElement("hostscript")
  237. for sr in self.script_results:
  238. hostscript_elem.appendChild(sr.to_dom_fragment(document))
  239. elem.appendChild(hostscript_elem)
  240. @@ -246,7 +246,7 @@ class Address(object):
  241. self.s = s
  242. def __eq__(self, other):
  243. - return self.__cmp__(other) == 0
  244. + return self.sort_key() == other.sort_key()
  245. def __ne__(self, other):
  246. return not self.__eq__(other)
  247. @@ -254,8 +254,8 @@ class Address(object):
  248. def __hash__(self):
  249. return hash(self.sort_key())
  250. - def __cmp__(self, other):
  251. - return cmp(self.sort_key(), other.sort_key())
  252. + def __lt__(self, other):
  253. + return self.sort_key() < other.sort_key()
  254. def __str__(self):
  255. return str(self.s)
  256. @@ -264,21 +264,21 @@ class Address(object):
  257. return self.s
  258. def new(type, s):
  259. - if type == u"ipv4":
  260. + if type == "ipv4":
  261. return IPv4Address(s)
  262. - elif type == u"ipv6":
  263. + elif type == "ipv6":
  264. return IPv6Address(s)
  265. - elif type == u"mac":
  266. + elif type == "mac":
  267. return MACAddress(s)
  268. else:
  269. - raise ValueError(u"Unknown address type %s." % type)
  270. + raise ValueError("Unknown address type %s." % type)
  271. new = staticmethod(new)
  272. def to_dom_fragment(self, document):
  273. frag = document.createDocumentFragment()
  274. - elem = document.createElement(u"address")
  275. - elem.setAttribute(u"addr", self.s)
  276. - elem.setAttribute(u"addrtype", self.type)
  277. + elem = document.createElement("address")
  278. + elem.setAttribute("addr", self.s)
  279. + elem.setAttribute("addrtype", self.type)
  280. frag.appendChild(elem)
  281. return frag
  282. @@ -287,21 +287,21 @@ class Address(object):
  283. class IPv4Address(Address):
  284. - type = property(lambda self: u"ipv4")
  285. + type = property(lambda self: "ipv4")
  286. def sort_key(self):
  287. return (0, self.s)
  288. class IPv6Address(Address):
  289. - type = property(lambda self: u"ipv6")
  290. + type = property(lambda self: "ipv6")
  291. def sort_key(self):
  292. return (1, self.s)
  293. class MACAddress(Address):
  294. - type = property(lambda self: u"mac")
  295. + type = property(lambda self: "mac")
  296. def sort_key(self):
  297. return (2, self.s)
  298. @@ -320,28 +320,25 @@ class Port(object):
  299. def state_string(self):
  300. if self.state is None:
  301. - return u"unknown"
  302. + return "unknown"
  303. else:
  304. - return unicode(self.state)
  305. + return str(self.state)
  306. def spec_string(self):
  307. - return u"%d/%s" % self.spec
  308. + return "%d/%s" % self.spec
  309. - def __cmp__(self, other):
  310. - d = cmp(self.spec, other.spec)
  311. - if d != 0:
  312. - return d
  313. - return cmp((self.spec, self.service, self.script_results),
  314. - (other.spec, other.service, other.script_results))
  315. + def __lt__(self, other):
  316. + return (self.spec, self.service, self.script_results) < (
  317. + other.spec, other.service, other.script_results)
  318. def to_dom_fragment(self, document):
  319. frag = document.createDocumentFragment()
  320. - elem = document.createElement(u"port")
  321. - elem.setAttribute(u"portid", unicode(self.spec[0]))
  322. - elem.setAttribute(u"protocol", self.spec[1])
  323. + elem = document.createElement("port")
  324. + elem.setAttribute("portid", str(self.spec[0]))
  325. + elem.setAttribute("protocol", self.spec[1])
  326. if self.state is not None:
  327. - state_elem = document.createElement(u"state")
  328. - state_elem.setAttribute(u"state", self.state)
  329. + state_elem = document.createElement("state")
  330. + state_elem.setAttribute("state", self.state)
  331. elem.appendChild(state_elem)
  332. elem.appendChild(self.service.to_dom_fragment(document))
  333. for sr in self.script_results:
  334. @@ -385,7 +382,7 @@ class Service(object):
  335. if len(parts) == 0:
  336. return None
  337. else:
  338. - return u"/".join(parts)
  339. + return "/".join(parts)
  340. def version_string(self):
  341. """Get a string like in the VERSION column of Nmap output."""
  342. @@ -395,17 +392,17 @@ class Service(object):
  343. if self.version is not None:
  344. parts.append(self.version)
  345. if self.extrainfo is not None:
  346. - parts.append(u"(%s)" % self.extrainfo)
  347. + parts.append("(%s)" % self.extrainfo)
  348. if len(parts) == 0:
  349. return None
  350. else:
  351. - return u" ".join(parts)
  352. + return " ".join(parts)
  353. def to_dom_fragment(self, document):
  354. frag = document.createDocumentFragment()
  355. - elem = document.createElement(u"service")
  356. - for attr in (u"name", u"product", u"version", u"extrainfo", u"tunnel"):
  357. + elem = document.createElement("service")
  358. + for attr in ("name", "product", "version", "extrainfo", "tunnel"):
  359. v = getattr(self, attr)
  360. if v is None:
  361. continue
  362. @@ -435,53 +432,53 @@ class ScriptResult(object):
  363. result = []
  364. lines = self.output.splitlines()
  365. if len(lines) > 0:
  366. - lines[0] = self.id + u": " + lines[0]
  367. + lines[0] = self.id + ": " + lines[0]
  368. for line in lines[:-1]:
  369. - result.append(u"| " + line)
  370. + result.append("| " + line)
  371. if len(lines) > 0:
  372. - result.append(u"|_ " + lines[-1])
  373. + result.append("|_ " + lines[-1])
  374. return result
  375. def to_dom_fragment(self, document):
  376. frag = document.createDocumentFragment()
  377. - elem = document.createElement(u"script")
  378. - elem.setAttribute(u"id", self.id)
  379. - elem.setAttribute(u"output", self.output)
  380. + elem = document.createElement("script")
  381. + elem.setAttribute("id", self.id)
  382. + elem.setAttribute("output", self.output)
  383. frag.appendChild(elem)
  384. return frag
  385. def format_banner(scan):
  386. """Format a startup banner more or less like Nmap does."""
  387. - scanner = u"Nmap"
  388. - if scan.scanner is not None and scan.scanner != u"nmap":
  389. + scanner = "Nmap"
  390. + if scan.scanner is not None and scan.scanner != "nmap":
  391. scanner = scan.scanner
  392. parts = [scanner]
  393. if scan.version is not None:
  394. parts.append(scan.version)
  395. - parts.append(u"scan")
  396. + parts.append("scan")
  397. if scan.start_date is not None:
  398. - parts.append(u"initiated %s" % scan.start_date.strftime(
  399. + parts.append("initiated %s" % scan.start_date.strftime(
  400. "%a %b %d %H:%M:%S %Y"))
  401. if scan.args is not None:
  402. - parts.append(u"as: %s" % scan.args)
  403. - return u" ".join(parts)
  404. + parts.append("as: %s" % scan.args)
  405. + return " ".join(parts)
  406. def print_script_result_diffs_text(title, script_results_a, script_results_b,
  407. script_result_diffs, f=sys.stdout):
  408. - table = Table(u"*")
  409. + table = Table("*")
  410. for sr_diff in script_result_diffs:
  411. sr_diff.append_to_port_table(table)
  412. if len(table) > 0:
  413. - print >> f
  414. + print(file=f)
  415. if len(script_results_b) == 0:
  416. - print >> f, u"-%s:" % title
  417. + print("-%s:" % title, file=f)
  418. elif len(script_results_a) == 0:
  419. - print >> f, u"+%s:" % title
  420. + print("+%s:" % title, file=f)
  421. else:
  422. - print >> f, u" %s:" % title
  423. - print >> f, table
  424. + print(" %s:" % title, file=f)
  425. + print(table, file=f)
  426. def script_result_diffs_to_dom_fragment(elem, script_results_a,
  427. @@ -489,13 +486,13 @@ def script_result_diffs_to_dom_fragment(elem, script_results_a,
  428. if len(script_results_a) == 0 and len(script_results_b) == 0:
  429. return document.createDocumentFragment()
  430. elif len(script_results_b) == 0:
  431. - a_elem = document.createElement(u"a")
  432. + a_elem = document.createElement("a")
  433. for sr in script_results_a:
  434. elem.appendChild(sr.to_dom_fragment(document))
  435. a_elem.appendChild(elem)
  436. return a_elem
  437. elif len(script_results_a) == 0:
  438. - b_elem = document.createElement(u"b")
  439. + b_elem = document.createElement("b")
  440. for sr in script_results_b:
  441. elem.appendChild(sr.to_dom_fragment(document))
  442. b_elem.appendChild(elem)
  443. @@ -581,10 +578,10 @@ class ScanDiffText(ScanDiff):
  444. banner_a = format_banner(self.scan_a)
  445. banner_b = format_banner(self.scan_b)
  446. if banner_a != banner_b:
  447. - print >> self.f, u"-%s" % banner_a
  448. - print >> self.f, u"+%s" % banner_b
  449. + print("-%s" % banner_a, file=self.f)
  450. + print("+%s" % banner_b, file=self.f)
  451. elif verbose:
  452. - print >> self.f, u" %s" % banner_a
  453. + print(" %s" % banner_a, file=self.f)
  454. def output_pre_scripts(self, pre_script_result_diffs):
  455. print_script_result_diffs_text("Pre-scan script results",
  456. @@ -597,7 +594,7 @@ class ScanDiffText(ScanDiff):
  457. post_script_result_diffs, self.f)
  458. def output_host_diff(self, h_diff):
  459. - print >> self.f
  460. + print(file=self.f)
  461. h_diff.print_text(self.f)
  462. def output_ending(self):
  463. @@ -622,8 +619,8 @@ class ScanDiffXML(ScanDiff):
  464. def output_beginning(self):
  465. self.writer.startDocument()
  466. - self.writer.startElement(u"nmapdiff", {u"version": NDIFF_XML_VERSION})
  467. - self.writer.startElement(u"scandiff", {})
  468. + self.writer.startElement("nmapdiff", {"version": NDIFF_XML_VERSION})
  469. + self.writer.startElement("scandiff", {})
  470. if self.nmaprun_differs():
  471. self.writer.frag_a(
  472. @@ -636,7 +633,7 @@ class ScanDiffXML(ScanDiff):
  473. def output_pre_scripts(self, pre_script_result_diffs):
  474. if len(pre_script_result_diffs) > 0 or verbose:
  475. - prescript_elem = self.document.createElement(u"prescript")
  476. + prescript_elem = self.document.createElement("prescript")
  477. frag = script_result_diffs_to_dom_fragment(
  478. prescript_elem, self.scan_a.pre_script_results,
  479. self.scan_b.pre_script_results, pre_script_result_diffs,
  480. @@ -646,7 +643,7 @@ class ScanDiffXML(ScanDiff):
  481. def output_post_scripts(self, post_script_result_diffs):
  482. if len(post_script_result_diffs) > 0 or verbose:
  483. - postscript_elem = self.document.createElement(u"postscript")
  484. + postscript_elem = self.document.createElement("postscript")
  485. frag = script_result_diffs_to_dom_fragment(
  486. postscript_elem, self.scan_a.post_script_results,
  487. self.scan_b.post_script_results, post_script_result_diffs,
  488. @@ -660,8 +657,8 @@ class ScanDiffXML(ScanDiff):
  489. frag.unlink()
  490. def output_ending(self):
  491. - self.writer.endElement(u"scandiff")
  492. - self.writer.endElement(u"nmapdiff")
  493. + self.writer.endElement("scandiff")
  494. + self.writer.endElement("nmapdiff")
  495. self.writer.endDocument()
  496. @@ -719,9 +716,9 @@ class HostDiff(object):
  497. self.cost += os_cost
  498. extraports_a = tuple((count, state)
  499. - for (state, count) in self.host_a.extraports.items())
  500. + for (state, count) in list(self.host_a.extraports.items()))
  501. extraports_b = tuple((count, state)
  502. - for (state, count) in self.host_b.extraports.items())
  503. + for (state, count) in list(self.host_b.extraports.items()))
  504. if extraports_a != extraports_b:
  505. self.extraports_changed = True
  506. self.cost += 1
  507. @@ -747,69 +744,69 @@ class HostDiff(object):
  508. # Names and addresses.
  509. if self.id_changed:
  510. if host_a.state is not None:
  511. - print >> f, u"-%s:" % host_a.format_name()
  512. + print("-%s:" % host_a.format_name(), file=f)
  513. if self.host_b.state is not None:
  514. - print >> f, u"+%s:" % host_b.format_name()
  515. + print("+%s:" % host_b.format_name(), file=f)
  516. else:
  517. - print >> f, u" %s:" % host_a.format_name()
  518. + print(" %s:" % host_a.format_name(), file=f)
  519. # State.
  520. if self.state_changed:
  521. if host_a.state is not None:
  522. - print >> f, u"-Host is %s." % host_a.state
  523. + print("-Host is %s." % host_a.state, file=f)
  524. if host_b.state is not None:
  525. - print >> f, u"+Host is %s." % host_b.state
  526. + print("+Host is %s." % host_b.state, file=f)
  527. elif verbose:
  528. - print >> f, u" Host is %s." % host_b.state
  529. + print(" Host is %s." % host_b.state, file=f)
  530. # Extraports.
  531. if self.extraports_changed:
  532. if len(host_a.extraports) > 0:
  533. - print >> f, u"-Not shown: %s" % host_a.extraports_string()
  534. + print("-Not shown: %s" % host_a.extraports_string(), file=f)
  535. if len(host_b.extraports) > 0:
  536. - print >> f, u"+Not shown: %s" % host_b.extraports_string()
  537. + print("+Not shown: %s" % host_b.extraports_string(), file=f)
  538. elif verbose:
  539. if len(host_a.extraports) > 0:
  540. - print >> f, u" Not shown: %s" % host_a.extraports_string()
  541. + print(" Not shown: %s" % host_a.extraports_string(), file=f)
  542. # Port table.
  543. - port_table = Table(u"** * * *")
  544. + port_table = Table("** * * *")
  545. if host_a.state is None:
  546. - mark = u"+"
  547. + mark = "+"
  548. elif host_b.state is None:
  549. - mark = u"-"
  550. + mark = "-"
  551. else:
  552. - mark = u" "
  553. - port_table.append((mark, u"PORT", u"STATE", u"SERVICE", u"VERSION"))
  554. + mark = " "
  555. + port_table.append((mark, "PORT", "STATE", "SERVICE", "VERSION"))
  556. for port in self.ports:
  557. port_diff = self.port_diffs[port]
  558. port_diff.append_to_port_table(port_table, host_a, host_b)
  559. if len(port_table) > 1:
  560. - print >> f, port_table
  561. + print(port_table, file=f)
  562. # OS changes.
  563. if self.os_changed or verbose:
  564. if len(host_a.os) > 0:
  565. if len(host_b.os) > 0:
  566. - print >> f, u" OS details:"
  567. + print(" OS details:", file=f)
  568. else:
  569. - print >> f, u"-OS details:"
  570. + print("-OS details:", file=f)
  571. elif len(host_b.os) > 0:
  572. - print >> f, u"+OS details:"
  573. + print("+OS details:", file=f)
  574. # os_diffs is a list of 5-tuples returned by
  575. # difflib.SequenceMatcher.
  576. for op, i1, i2, j1, j2 in self.os_diffs:
  577. if op == "replace" or op == "delete":
  578. for i in range(i1, i2):
  579. - print >> f, "- %s" % host_a.os[i]
  580. + print("- %s" % host_a.os[i], file=f)
  581. if op == "replace" or op == "insert":
  582. for i in range(j1, j2):
  583. - print >> f, "+ %s" % host_b.os[i]
  584. + print("+ %s" % host_b.os[i], file=f)
  585. if op == "equal":
  586. for i in range(i1, i2):
  587. - print >> f, " %s" % host_a.os[i]
  588. + print(" %s" % host_a.os[i], file=f)
  589. print_script_result_diffs_text("Host script results",
  590. host_a.script_results, host_b.script_results,
  591. @@ -820,32 +817,32 @@ class HostDiff(object):
  592. host_b = self.host_b
  593. frag = document.createDocumentFragment()
  594. - hostdiff_elem = document.createElement(u"hostdiff")
  595. + hostdiff_elem = document.createElement("hostdiff")
  596. frag.appendChild(hostdiff_elem)
  597. if host_a.state is None or host_b.state is None:
  598. # The host is missing in one scan. Output the whole thing.
  599. if host_a.state is not None:
  600. - a_elem = document.createElement(u"a")
  601. + a_elem = document.createElement("a")
  602. a_elem.appendChild(host_a.to_dom_fragment(document))
  603. hostdiff_elem.appendChild(a_elem)
  604. elif host_b.state is not None:
  605. - b_elem = document.createElement(u"b")
  606. + b_elem = document.createElement("b")
  607. b_elem.appendChild(host_b.to_dom_fragment(document))
  608. hostdiff_elem.appendChild(b_elem)
  609. return frag
  610. - host_elem = document.createElement(u"host")
  611. + host_elem = document.createElement("host")
  612. # State.
  613. if host_a.state == host_b.state:
  614. if verbose:
  615. host_elem.appendChild(host_a.state_to_dom_fragment(document))
  616. else:
  617. - a_elem = document.createElement(u"a")
  618. + a_elem = document.createElement("a")
  619. a_elem.appendChild(host_a.state_to_dom_fragment(document))
  620. host_elem.appendChild(a_elem)
  621. - b_elem = document.createElement(u"b")
  622. + b_elem = document.createElement("b")
  623. b_elem.appendChild(host_b.state_to_dom_fragment(document))
  624. host_elem.appendChild(b_elem)
  625. @@ -854,31 +851,31 @@ class HostDiff(object):
  626. addrset_b = set(host_b.addresses)
  627. for addr in sorted(addrset_a.intersection(addrset_b)):
  628. host_elem.appendChild(addr.to_dom_fragment(document))
  629. - a_elem = document.createElement(u"a")
  630. + a_elem = document.createElement("a")
  631. for addr in sorted(addrset_a - addrset_b):
  632. a_elem.appendChild(addr.to_dom_fragment(document))
  633. if a_elem.hasChildNodes():
  634. host_elem.appendChild(a_elem)
  635. - b_elem = document.createElement(u"b")
  636. + b_elem = document.createElement("b")
  637. for addr in sorted(addrset_b - addrset_a):
  638. b_elem.appendChild(addr.to_dom_fragment(document))
  639. if b_elem.hasChildNodes():
  640. host_elem.appendChild(b_elem)
  641. # Host names.
  642. - hostnames_elem = document.createElement(u"hostnames")
  643. + hostnames_elem = document.createElement("hostnames")
  644. hostnameset_a = set(host_a.hostnames)
  645. hostnameset_b = set(host_b.hostnames)
  646. for hostname in sorted(hostnameset_a.intersection(hostnameset_b)):
  647. hostnames_elem.appendChild(
  648. host_a.hostname_to_dom_fragment(document, hostname))
  649. - a_elem = document.createElement(u"a")
  650. + a_elem = document.createElement("a")
  651. for hostname in sorted(hostnameset_a - hostnameset_b):
  652. a_elem.appendChild(
  653. host_a.hostname_to_dom_fragment(document, hostname))
  654. if a_elem.hasChildNodes():
  655. hostnames_elem.appendChild(a_elem)
  656. - b_elem = document.createElement(u"b")
  657. + b_elem = document.createElement("b")
  658. for hostname in sorted(hostnameset_b - hostnameset_a):
  659. b_elem.appendChild(
  660. host_b.hostname_to_dom_fragment(document, hostname))
  661. @@ -887,15 +884,15 @@ class HostDiff(object):
  662. if hostnames_elem.hasChildNodes():
  663. host_elem.appendChild(hostnames_elem)
  664. - ports_elem = document.createElement(u"ports")
  665. + ports_elem = document.createElement("ports")
  666. # Extraports.
  667. if host_a.extraports == host_b.extraports:
  668. ports_elem.appendChild(host_a.extraports_to_dom_fragment(document))
  669. else:
  670. - a_elem = document.createElement(u"a")
  671. + a_elem = document.createElement("a")
  672. a_elem.appendChild(host_a.extraports_to_dom_fragment(document))
  673. ports_elem.appendChild(a_elem)
  674. - b_elem = document.createElement(u"b")
  675. + b_elem = document.createElement("b")
  676. b_elem.appendChild(host_b.extraports_to_dom_fragment(document))
  677. ports_elem.appendChild(b_elem)
  678. # Port list.
  679. @@ -911,18 +908,18 @@ class HostDiff(object):
  680. # OS changes.
  681. if self.os_changed or verbose:
  682. - os_elem = document.createElement(u"os")
  683. + os_elem = document.createElement("os")
  684. # os_diffs is a list of 5-tuples returned by
  685. # difflib.SequenceMatcher.
  686. for op, i1, i2, j1, j2 in self.os_diffs:
  687. if op == "replace" or op == "delete":
  688. - a_elem = document.createElement(u"a")
  689. + a_elem = document.createElement("a")
  690. for i in range(i1, i2):
  691. a_elem.appendChild(host_a.os_to_dom_fragment(
  692. document, host_a.os[i]))
  693. os_elem.appendChild(a_elem)
  694. if op == "replace" or op == "insert":
  695. - b_elem = document.createElement(u"b")
  696. + b_elem = document.createElement("b")
  697. for i in range(j1, j2):
  698. b_elem.appendChild(host_b.os_to_dom_fragment(
  699. document, host_b.os[i]))
  700. @@ -936,7 +933,7 @@ class HostDiff(object):
  701. # Host script changes.
  702. if len(self.script_result_diffs) > 0 or verbose:
  703. - hostscript_elem = document.createElement(u"hostscript")
  704. + hostscript_elem = document.createElement("hostscript")
  705. host_elem.appendChild(script_result_diffs_to_dom_fragment(
  706. hostscript_elem, host_a.script_results,
  707. host_b.script_results, self.script_result_diffs,
  708. @@ -989,38 +986,38 @@ class PortDiff(object):
  709. self.port_b.service.version_string()]
  710. if a_columns == b_columns:
  711. if verbose or self.script_result_diffs > 0:
  712. - table.append([u" "] + a_columns)
  713. + table.append([" "] + a_columns)
  714. else:
  715. if not host_a.is_extraports(self.port_a.state):
  716. - table.append([u"-"] + a_columns)
  717. + table.append(["-"] + a_columns)
  718. if not host_b.is_extraports(self.port_b.state):
  719. - table.append([u"+"] + b_columns)
  720. + table.append(["+"] + b_columns)
  721. for sr_diff in self.script_result_diffs:
  722. sr_diff.append_to_port_table(table)
  723. def to_dom_fragment(self, document):
  724. frag = document.createDocumentFragment()
  725. - portdiff_elem = document.createElement(u"portdiff")
  726. + portdiff_elem = document.createElement("portdiff")
  727. frag.appendChild(portdiff_elem)
  728. if (self.port_a.spec == self.port_b.spec and
  729. self.port_a.state == self.port_b.state):
  730. - port_elem = document.createElement(u"port")
  731. - port_elem.setAttribute(u"portid", unicode(self.port_a.spec[0]))
  732. - port_elem.setAttribute(u"protocol", self.port_a.spec[1])
  733. + port_elem = document.createElement("port")
  734. + port_elem.setAttribute("portid", str(self.port_a.spec[0]))
  735. + port_elem.setAttribute("protocol", self.port_a.spec[1])
  736. if self.port_a.state is not None:
  737. - state_elem = document.createElement(u"state")
  738. - state_elem.setAttribute(u"state", self.port_a.state)
  739. + state_elem = document.createElement("state")
  740. + state_elem.setAttribute("state", self.port_a.state)
  741. port_elem.appendChild(state_elem)
  742. if self.port_a.service == self.port_b.service:
  743. port_elem.appendChild(
  744. self.port_a.service.to_dom_fragment(document))
  745. else:
  746. - a_elem = document.createElement(u"a")
  747. + a_elem = document.createElement("a")
  748. a_elem.appendChild(
  749. self.port_a.service.to_dom_fragment(document))
  750. port_elem.appendChild(a_elem)
  751. - b_elem = document.createElement(u"b")
  752. + b_elem = document.createElement("b")
  753. b_elem.appendChild(
  754. self.port_b.service.to_dom_fragment(document))
  755. port_elem.appendChild(b_elem)
  756. @@ -1028,10 +1025,10 @@ class PortDiff(object):
  757. port_elem.appendChild(sr_diff.to_dom_fragment(document))
  758. portdiff_elem.appendChild(port_elem)
  759. else:
  760. - a_elem = document.createElement(u"a")
  761. + a_elem = document.createElement("a")
  762. a_elem.appendChild(self.port_a.to_dom_fragment(document))
  763. portdiff_elem.appendChild(a_elem)
  764. - b_elem = document.createElement(u"b")
  765. + b_elem = document.createElement("b")
  766. b_elem.appendChild(self.port_b.to_dom_fragment(document))
  767. portdiff_elem.appendChild(b_elem)
  768. @@ -1086,13 +1083,13 @@ class ScriptResultDiff(object):
  769. for op, i1, i2, j1, j2 in diffs.get_opcodes():
  770. if op == "replace" or op == "delete":
  771. for k in range(i1, i2):
  772. - table.append_raw(u"-" + a_lines[k])
  773. + table.append_raw("-" + a_lines[k])
  774. if op == "replace" or op == "insert":
  775. for k in range(j1, j2):
  776. - table.append_raw(u"+" + b_lines[k])
  777. + table.append_raw("+" + b_lines[k])
  778. if op == "equal":
  779. for k in range(i1, i2):
  780. - table.append_raw(u" " + a_lines[k])
  781. + table.append_raw(" " + a_lines[k])
  782. def to_dom_fragment(self, document):
  783. frag = document.createDocumentFragment()
  784. @@ -1102,11 +1099,11 @@ class ScriptResultDiff(object):
  785. frag.appendChild(self.sr_a.to_dom_fragment(document))
  786. else:
  787. if self.sr_a is not None:
  788. - a_elem = document.createElement(u"a")
  789. + a_elem = document.createElement("a")
  790. a_elem.appendChild(self.sr_a.to_dom_fragment(document))
  791. frag.appendChild(a_elem)
  792. if self.sr_b is not None:
  793. - b_elem = document.createElement(u"b")
  794. + b_elem = document.createElement("b")
  795. b_elem.appendChild(self.sr_b.to_dom_fragment(document))
  796. frag.appendChild(b_elem)
  797. return frag
  798. @@ -1120,7 +1117,7 @@ class Table(object):
  799. copied to the output."""
  800. self.widths = []
  801. self.rows = []
  802. - self.prefix = u""
  803. + self.prefix = ""
  804. self.padding = []
  805. j = 0
  806. while j < len(template) and template[j] != "*":
  807. @@ -1145,7 +1142,7 @@ class Table(object):
  808. for i in range(len(row)):
  809. if row[i] is None:
  810. - s = u""
  811. + s = ""
  812. else:
  813. s = str(row[i])
  814. if i == len(self.widths):
  815. @@ -1167,7 +1164,7 @@ class Table(object):
  816. for row in self.rows:
  817. parts = [self.prefix]
  818. i = 0
  819. - if isinstance(row, basestring):
  820. + if isinstance(row, str):
  821. # A raw string.
  822. lines.append(row)
  823. else:
  824. @@ -1176,13 +1173,13 @@ class Table(object):
  825. if i < len(self.padding):
  826. parts.append(self.padding[i])
  827. i += 1
  828. - lines.append(u"".join(parts).rstrip())
  829. - return u"\n".join(lines)
  830. + lines.append("".join(parts).rstrip())
  831. + return "\n".join(lines)
  832. def warn(str):
  833. """Print a warning to stderr."""
  834. - print >> sys.stderr, str
  835. + print(str, file=sys.stderr)
  836. class NmapContentHandler(xml.sax.handler.ContentHandler):
  837. @@ -1200,22 +1197,22 @@ class NmapContentHandler(xml.sax.handler.ContentHandler):
  838. self.current_port = None
  839. self._start_elem_handlers = {
  840. - u"nmaprun": self._start_nmaprun,
  841. - u"host": self._start_host,
  842. - u"status": self._start_status,
  843. - u"address": self._start_address,
  844. - u"hostname": self._start_hostname,
  845. - u"extraports": self._start_extraports,
  846. - u"port": self._start_port,
  847. - u"state": self._start_state,
  848. - u"service": self._start_service,
  849. - u"script": self._start_script,
  850. - u"osmatch": self._start_osmatch,
  851. - u"finished": self._start_finished,
  852. + "nmaprun": self._start_nmaprun,
  853. + "host": self._start_host,
  854. + "status": self._start_status,
  855. + "address": self._start_address,
  856. + "hostname": self._start_hostname,
  857. + "extraports": self._start_extraports,
  858. + "port": self._start_port,
  859. + "state": self._start_state,
  860. + "service": self._start_service,
  861. + "script": self._start_script,
  862. + "osmatch": self._start_osmatch,
  863. + "finished": self._start_finished,
  864. }
  865. self._end_elem_handlers = {
  866. - u'host': self._end_host,
  867. - u'port': self._end_port,
  868. + 'host': self._end_host,
  869. + 'port': self._end_port,
  870. }
  871. def parent_element(self):
  872. @@ -1245,68 +1242,68 @@ class NmapContentHandler(xml.sax.handler.ContentHandler):
  873. def _start_nmaprun(self, name, attrs):
  874. assert self.parent_element() is None
  875. if "start" in attrs:
  876. - start_timestamp = int(attrs.get(u"start"))
  877. + start_timestamp = int(attrs.get("start"))
  878. self.scan.start_date = datetime.datetime.fromtimestamp(
  879. start_timestamp)
  880. - self.scan.scanner = attrs.get(u"scanner")
  881. - self.scan.args = attrs.get(u"args")
  882. - self.scan.version = attrs.get(u"version")
  883. + self.scan.scanner = attrs.get("scanner")
  884. + self.scan.args = attrs.get("args")
  885. + self.scan.version = attrs.get("version")
  886. def _start_host(self, name, attrs):
  887. - assert self.parent_element() == u"nmaprun"
  888. + assert self.parent_element() == "nmaprun"
  889. self.current_host = Host()
  890. self.scan.hosts.append(self.current_host)
  891. def _start_status(self, name, attrs):
  892. - assert self.parent_element() == u"host"
  893. + assert self.parent_element() == "host"
  894. assert self.current_host is not None
  895. - state = attrs.get(u"state")
  896. + state = attrs.get("state")
  897. if state is None:
  898. warn(u'%s element of host %s is missing the "state" attribute; '
  899. - 'assuming \unknown\.' % (
  900. + r'assuming \unknown\.' % (
  901. name, self.current_host.format_name()))
  902. return
  903. self.current_host.state = state
  904. def _start_address(self, name, attrs):
  905. - assert self.parent_element() == u"host"
  906. + assert self.parent_element() == "host"
  907. assert self.current_host is not None
  908. - addr = attrs.get(u"addr")
  909. + addr = attrs.get("addr")
  910. if addr is None:
  911. - warn(u'%s element of host %s is missing the "addr" '
  912. + warn('%s element of host %s is missing the "addr" '
  913. 'attribute; skipping.' % (
  914. name, self.current_host.format_name()))
  915. return
  916. - addrtype = attrs.get(u"addrtype", u"ipv4")
  917. + addrtype = attrs.get("addrtype", "ipv4")
  918. self.current_host.add_address(Address.new(addrtype, addr))
  919. def _start_hostname(self, name, attrs):
  920. - assert self.parent_element() == u"hostnames"
  921. + assert self.parent_element() == "hostnames"
  922. assert self.current_host is not None
  923. - hostname = attrs.get(u"name")
  924. + hostname = attrs.get("name")
  925. if hostname is None:
  926. - warn(u'%s element of host %s is missing the "name" '
  927. + warn('%s element of host %s is missing the "name" '
  928. 'attribute; skipping.' % (
  929. name, self.current_host.format_name()))
  930. return
  931. self.current_host.add_hostname(hostname)
  932. def _start_extraports(self, name, attrs):
  933. - assert self.parent_element() == u"ports"
  934. + assert self.parent_element() == "ports"
  935. assert self.current_host is not None
  936. - state = attrs.get(u"state")
  937. + state = attrs.get("state")
  938. if state is None:
  939. - warn(u'%s element of host %s is missing the "state" '
  940. + warn('%s element of host %s is missing the "state" '
  941. 'attribute; assuming "unknown".' % (
  942. name, self.current_host.format_name()))
  943. state = None
  944. if state in self.current_host.extraports:
  945. - warn(u'Duplicate extraports state "%s" in host %s.' % (
  946. + warn('Duplicate extraports state "%s" in host %s.' % (
  947. state, self.current_host.format_name()))
  948. - count = attrs.get(u"count")
  949. + count = attrs.get("count")
  950. if count is None:
  951. - warn(u'%s element of host %s is missing the "count" '
  952. + warn('%s element of host %s is missing the "count" '
  953. 'attribute; assuming 0.' % (
  954. name, self.current_host.format_name()))
  955. count = 0
  956. @@ -1314,99 +1311,99 @@ class NmapContentHandler(xml.sax.handler.ContentHandler):
  957. try:
  958. count = int(count)
  959. except ValueError:
  960. - warn(u"Can't convert extraports count \"%s\" "
  961. + warn("Can't convert extraports count \"%s\" "
  962. "to an integer in host %s; assuming 0." % (
  963. - attrs[u"count"], self.current_host.format_name()))
  964. + attrs["count"], self.current_host.format_name()))
  965. count = 0
  966. self.current_host.extraports[state] = count
  967. def _start_port(self, name, attrs):
  968. - assert self.parent_element() == u"ports"
  969. + assert self.parent_element() == "ports"
  970. assert self.current_host is not None
  971. - portid_str = attrs.get(u"portid")
  972. + portid_str = attrs.get("portid")
  973. if portid_str is None:
  974. - warn(u'%s element of host %s missing the "portid" '
  975. + warn('%s element of host %s missing the "portid" '
  976. 'attribute; skipping.' % (
  977. name, self.current_host.format_name()))
  978. return
  979. try:
  980. portid = int(portid_str)
  981. except ValueError:
  982. - warn(u"Can't convert portid \"%s\" to an integer "
  983. + warn("Can't convert portid \"%s\" to an integer "
  984. "in host %s; skipping port." % (
  985. portid_str, self.current_host.format_name()))
  986. return
  987. - protocol = attrs.get(u"protocol")
  988. + protocol = attrs.get("protocol")
  989. if protocol is None:
  990. - warn(u'%s element of host %s missing the "protocol" '
  991. + warn('%s element of host %s missing the "protocol" '
  992. 'attribute; skipping.' % (
  993. name, self.current_host.format_name()))
  994. return
  995. self.current_port = Port((portid, protocol))
  996. def _start_state(self, name, attrs):
  997. - assert self.parent_element() == u"port"
  998. + assert self.parent_element() == "port"
  999. assert self.current_host is not None
  1000. if self.current_port is None:
  1001. return
  1002. if "state" not in attrs:
  1003. - warn(u'%s element of port %s is missing the "state" '
  1004. + warn('%s element of port %s is missing the "state" '
  1005. 'attribute; assuming "unknown".' % (
  1006. name, self.current_port.spec_string()))
  1007. return
  1008. - self.current_port.state = attrs[u"state"]
  1009. + self.current_port.state = attrs["state"]
  1010. self.current_host.add_port(self.current_port)
  1011. def _start_service(self, name, attrs):
  1012. - assert self.parent_element() == u"port"
  1013. + assert self.parent_element() == "port"
  1014. assert self.current_host is not None
  1015. if self.current_port is None:
  1016. return
  1017. - self.current_port.service.name = attrs.get(u"name")
  1018. - self.current_port.service.product = attrs.get(u"product")
  1019. - self.current_port.service.version = attrs.get(u"version")
  1020. - self.current_port.service.extrainfo = attrs.get(u"extrainfo")
  1021. - self.current_port.service.tunnel = attrs.get(u"tunnel")
  1022. + self.current_port.service.name = attrs.get("name")
  1023. + self.current_port.service.product = attrs.get("product")
  1024. + self.current_port.service.version = attrs.get("version")
  1025. + self.current_port.service.extrainfo = attrs.get("extrainfo")
  1026. + self.current_port.service.tunnel = attrs.get("tunnel")
  1027. def _start_script(self, name, attrs):
  1028. result = ScriptResult()
  1029. - result.id = attrs.get(u"id")
  1030. + result.id = attrs.get("id")
  1031. if result.id is None:
  1032. - warn(u'%s element missing the "id" attribute; skipping.' % name)
  1033. + warn('%s element missing the "id" attribute; skipping.' % name)
  1034. return
  1035. - result.output = attrs.get(u"output")
  1036. + result.output = attrs.get("output")
  1037. if result.output is None:
  1038. - warn(u'%s element missing the "output" attribute; skipping.'
  1039. + warn('%s element missing the "output" attribute; skipping.'
  1040. % name)
  1041. return
  1042. - if self.parent_element() == u"prescript":
  1043. + if self.parent_element() == "prescript":
  1044. self.scan.pre_script_results.append(result)
  1045. - elif self.parent_element() == u"postscript":
  1046. + elif self.parent_element() == "postscript":
  1047. self.scan.post_script_results.append(result)
  1048. - elif self.parent_element() == u"hostscript":
  1049. + elif self.parent_element() == "hostscript":
  1050. self.current_host.script_results.append(result)
  1051. - elif self.parent_element() == u"port":
  1052. + elif self.parent_element() == "port":
  1053. self.current_port.script_results.append(result)
  1054. else:
  1055. - warn(u"%s element not inside prescript, postscript, hostscript, "
  1056. + warn("%s element not inside prescript, postscript, hostscript, "
  1057. "or port element; ignoring." % name)
  1058. return
  1059. def _start_osmatch(self, name, attrs):
  1060. - assert self.parent_element() == u"os"
  1061. + assert self.parent_element() == "os"
  1062. assert self.current_host is not None
  1063. if "name" not in attrs:
  1064. - warn(u'%s element of host %s is missing the "name" '
  1065. + warn('%s element of host %s is missing the "name" '
  1066. 'attribute; skipping.' % (
  1067. name, self.current_host.format_name()))
  1068. return
  1069. - self.current_host.os.append(attrs[u"name"])
  1070. + self.current_host.os.append(attrs["name"])
  1071. def _start_finished(self, name, attrs):
  1072. - assert self.parent_element() == u"runstats"
  1073. + assert self.parent_element() == "runstats"
  1074. if "time" in attrs:
  1075. - end_timestamp = int(attrs.get(u"time"))
  1076. + end_timestamp = int(attrs.get("time"))
  1077. self.scan.end_date = datetime.datetime.fromtimestamp(end_timestamp)
  1078. def _end_host(self, name):
  1079. @@ -1425,23 +1422,23 @@ class XMLWriter (xml.sax.saxutils.XMLGenerator):
  1080. def frag(self, frag):
  1081. for node in frag.childNodes:
  1082. - node.writexml(self.f, newl=u"\n")
  1083. + node.writexml(self.f, newl="\n")
  1084. def frag_a(self, frag):
  1085. - self.startElement(u"a", {})
  1086. + self.startElement("a", {})
  1087. for node in frag.childNodes:
  1088. - node.writexml(self.f, newl=u"\n")
  1089. - self.endElement(u"a")
  1090. + node.writexml(self.f, newl="\n")
  1091. + self.endElement("a")
  1092. def frag_b(self, frag):
  1093. - self.startElement(u"b", {})
  1094. + self.startElement("b", {})
  1095. for node in frag.childNodes:
  1096. - node.writexml(self.f, newl=u"\n")
  1097. - self.endElement(u"b")
  1098. + node.writexml(self.f, newl="\n")
  1099. + self.endElement("b")
  1100. def usage():
  1101. - print u"""\
  1102. + print("""\
  1103. Usage: %s [option] FILE1 FILE2
  1104. Compare two Nmap XML files and display a list of their differences.
  1105. Differences include host state changes, port state changes, and changes to
  1106. @@ -1451,7 +1448,7 @@ service and OS detection.
  1107. -v, --verbose also show hosts and ports that haven't changed.
  1108. --text display output in text format (default)
  1109. --xml display output in XML format\
  1110. -""" % sys.argv[0]
  1111. +""" % sys.argv[0])
  1112. EXIT_EQUAL = 0
  1113. EXIT_DIFFERENT = 1
  1114. @@ -1459,8 +1456,8 @@ EXIT_ERROR = 2
  1115. def usage_error(msg):
  1116. - print >> sys.stderr, u"%s: %s" % (sys.argv[0], msg)
  1117. - print >> sys.stderr, u"Try '%s -h' for help." % sys.argv[0]
  1118. + print("%s: %s" % (sys.argv[0], msg), file=sys.stderr)
  1119. + print("Try '%s -h' for help." % sys.argv[0], file=sys.stderr)
  1120. sys.exit(EXIT_ERROR)
  1121. @@ -1471,7 +1468,7 @@ def main():
  1122. try:
  1123. opts, input_filenames = getopt.gnu_getopt(
  1124. sys.argv[1:], "hv", ["help", "text", "verbose", "xml"])
  1125. - except getopt.GetoptError, e:
  1126. + except getopt.GetoptError as e:
  1127. usage_error(e.msg)
  1128. for o, a in opts:
  1129. if o == "-h" or o == "--help":
  1130. @@ -1481,15 +1478,15 @@ def main():
  1131. verbose = True
  1132. elif o == "--text":
  1133. if output_format is not None and output_format != "text":
  1134. - usage_error(u"contradictory output format options.")
  1135. + usage_error("contradictory output format options.")
  1136. output_format = "text"
  1137. elif o == "--xml":
  1138. if output_format is not None and output_format != "xml":
  1139. - usage_error(u"contradictory output format options.")
  1140. + usage_error("contradictory output format options.")
  1141. output_format = "xml"
  1142. if len(input_filenames) != 2:
  1143. - usage_error(u"need exactly two input filenames.")
  1144. + usage_error("need exactly two input filenames.")
  1145. if output_format is None:
  1146. output_format = "text"
  1147. @@ -1502,8 +1499,8 @@ def main():
  1148. scan_a.load_from_file(filename_a)
  1149. scan_b = Scan()
  1150. scan_b.load_from_file(filename_b)
  1151. - except IOError, e:
  1152. - print >> sys.stderr, u"Can't open file: %s" % str(e)
  1153. + except IOError as e:
  1154. + print("Can't open file: %s" % str(e), file=sys.stderr)
  1155. sys.exit(EXIT_ERROR)
  1156. if output_format == "text":
  1157. diff --git a/ndiff/ndifftest.py b/ndiff/ndifftest.py
  1158. index 2fa4ae0..27fc525 100755
  1159. --- a/ndiff/ndifftest.py
  1160. +++ b/ndiff/ndifftest.py
  1161. @@ -1,4 +1,4 @@
  1162. -#!/usr/bin/env python
  1163. +#!/usr/bin/env python3
  1164. # Unit tests for Ndiff.
  1165. @@ -22,7 +22,7 @@ for x in dir(ndiff):
  1166. sys.dont_write_bytecode = dont_write_bytecode
  1167. del dont_write_bytecode
  1168. -import StringIO
  1169. +import io
  1170. class scan_test(unittest.TestCase):
  1171. @@ -52,7 +52,7 @@ class scan_test(unittest.TestCase):
  1172. scan.load_from_file("test-scans/single.xml")
  1173. host = scan.hosts[0]
  1174. self.assertEqual(len(host.ports), 5)
  1175. - self.assertEqual(host.extraports.items(), [("filtered", 95)])
  1176. + self.assertEqual(list(host.extraports.items()), [("filtered", 95)])
  1177. def test_extraports_multi(self):
  1178. """Test that the correct number of known ports is returned when there
  1179. @@ -68,9 +68,9 @@ class scan_test(unittest.TestCase):
  1180. """Test that nmaprun information is recorded."""
  1181. scan = Scan()
  1182. scan.load_from_file("test-scans/empty.xml")
  1183. - self.assertEqual(scan.scanner, u"nmap")
  1184. - self.assertEqual(scan.version, u"4.90RC2")
  1185. - self.assertEqual(scan.args, u"nmap -oX empty.xml -p 1-100")
  1186. + self.assertEqual(scan.scanner, "nmap")
  1187. + self.assertEqual(scan.version, "4.90RC2")
  1188. + self.assertEqual(scan.args, "nmap -oX empty.xml -p 1-100")
  1189. def test_addresses(self):
  1190. """Test that addresses are recorded."""
  1191. @@ -84,7 +84,7 @@ class scan_test(unittest.TestCase):
  1192. scan = Scan()
  1193. scan.load_from_file("test-scans/simple.xml")
  1194. host = scan.hosts[0]
  1195. - self.assertEqual(host.hostnames, [u"scanme.nmap.org"])
  1196. + self.assertEqual(host.hostnames, ["scanme.nmap.org"])
  1197. def test_os(self):
  1198. """Test that OS information is recorded."""
  1199. @@ -99,7 +99,7 @@ class scan_test(unittest.TestCase):
  1200. scan.load_from_file("test-scans/complex.xml")
  1201. host = scan.hosts[0]
  1202. self.assertTrue(len(host.script_results) > 0)
  1203. - self.assertTrue(len(host.ports[(22, u"tcp")].script_results) > 0)
  1204. + self.assertTrue(len(host.ports[(22, "tcp")].script_results) > 0)
  1205. # This test is commented out because Nmap XML doesn't store any information
  1206. # about down hosts, not even the fact that they are down. Recovering the list
  1207. @@ -128,16 +128,16 @@ class host_test(unittest.TestCase):
  1208. def test_format_name(self):
  1209. h = Host()
  1210. - self.assertTrue(isinstance(h.format_name(), basestring))
  1211. - h.add_address(IPv4Address(u"127.0.0.1"))
  1212. - self.assertTrue(u"127.0.0.1" in h.format_name())
  1213. + self.assertTrue(isinstance(h.format_name(), str))
  1214. + h.add_address(IPv4Address("127.0.0.1"))
  1215. + self.assertTrue("127.0.0.1" in h.format_name())
  1216. h.add_address(IPv6Address("::1"))
  1217. - self.assertTrue(u"127.0.0.1" in h.format_name())
  1218. - self.assertTrue(u"::1" in h.format_name())
  1219. - h.add_hostname(u"localhost")
  1220. - self.assertTrue(u"127.0.0.1" in h.format_name())
  1221. - self.assertTrue(u"::1" in h.format_name())
  1222. - self.assertTrue(u"localhost" in h.format_name())
  1223. + self.assertTrue("127.0.0.1" in h.format_name())
  1224. + self.assertTrue("::1" in h.format_name())
  1225. + h.add_hostname("localhost")
  1226. + self.assertTrue("127.0.0.1" in h.format_name())
  1227. + self.assertTrue("::1" in h.format_name())
  1228. + self.assertTrue("localhost" in h.format_name())
  1229. def test_empty_get_port(self):
  1230. h = Host()
  1231. @@ -197,8 +197,8 @@ class host_test(unittest.TestCase):
  1232. h = s.hosts[0]
  1233. self.assertEqual(len(h.ports), 5)
  1234. self.assertEqual(len(h.extraports), 1)
  1235. - self.assertEqual(h.extraports.keys()[0], u"filtered")
  1236. - self.assertEqual(h.extraports.values()[0], 95)
  1237. + self.assertEqual(list(h.extraports.keys())[0], "filtered")
  1238. + self.assertEqual(list(h.extraports.values())[0], 95)
  1239. self.assertEqual(h.state, "up")
  1240. @@ -241,13 +241,13 @@ class port_test(unittest.TestCase):
  1241. """Test the Port class."""
  1242. def test_spec_string(self):
  1243. p = Port((10, "tcp"))
  1244. - self.assertEqual(p.spec_string(), u"10/tcp")
  1245. + self.assertEqual(p.spec_string(), "10/tcp")
  1246. p = Port((100, "ip"))
  1247. - self.assertEqual(p.spec_string(), u"100/ip")
  1248. + self.assertEqual(p.spec_string(), "100/ip")
  1249. def test_state_string(self):
  1250. p = Port((10, "tcp"))
  1251. - self.assertEqual(p.state_string(), u"unknown")
  1252. + self.assertEqual(p.state_string(), "unknown")
  1253. class service_test(unittest.TestCase):
  1254. @@ -255,47 +255,47 @@ class service_test(unittest.TestCase):
  1255. def test_compare(self):
  1256. """Test that services with the same contents compare equal."""
  1257. a = Service()
  1258. - a.name = u"ftp"
  1259. - a.product = u"FooBar FTP"
  1260. - a.version = u"1.1.1"
  1261. - a.tunnel = u"ssl"
  1262. + a.name = "ftp"
  1263. + a.product = "FooBar FTP"
  1264. + a.version = "1.1.1"
  1265. + a.tunnel = "ssl"
  1266. self.assertEqual(a, a)
  1267. b = Service()
  1268. - b.name = u"ftp"
  1269. - b.product = u"FooBar FTP"
  1270. - b.version = u"1.1.1"
  1271. - b.tunnel = u"ssl"
  1272. + b.name = "ftp"
  1273. + b.product = "FooBar FTP"
  1274. + b.version = "1.1.1"
  1275. + b.tunnel = "ssl"
  1276. self.assertEqual(a, b)
  1277. - b.name = u"http"
  1278. + b.name = "http"
  1279. self.assertNotEqual(a, b)
  1280. c = Service()
  1281. self.assertNotEqual(a, c)
  1282. def test_tunnel(self):
  1283. serv = Service()
  1284. - serv.name = u"http"
  1285. - serv.tunnel = u"ssl"
  1286. - self.assertEqual(serv.name_string(), u"ssl/http")
  1287. + serv.name = "http"
  1288. + serv.tunnel = "ssl"
  1289. + self.assertEqual(serv.name_string(), "ssl/http")
  1290. def test_version_string(self):
  1291. serv = Service()
  1292. - serv.product = u"FooBar"
  1293. + serv.product = "FooBar"
  1294. self.assertTrue(len(serv.version_string()) > 0)
  1295. serv = Service()
  1296. - serv.version = u"1.2.3"
  1297. + serv.version = "1.2.3"
  1298. self.assertTrue(len(serv.version_string()) > 0)
  1299. serv = Service()
  1300. - serv.extrainfo = u"misconfigured"
  1301. + serv.extrainfo = "misconfigured"
  1302. self.assertTrue(len(serv.version_string()) > 0)
  1303. serv = Service()
  1304. - serv.product = u"FooBar"
  1305. - serv.version = u"1.2.3"
  1306. + serv.product = "FooBar"
  1307. + serv.version = "1.2.3"
  1308. # Must match Nmap output.
  1309. self.assertEqual(serv.version_string(),
  1310. - u"%s %s" % (serv.product, serv.version))
  1311. - serv.extrainfo = u"misconfigured"
  1312. + "%s %s" % (serv.product, serv.version))
  1313. + serv.extrainfo = "misconfigured"
  1314. self.assertEqual(serv.version_string(),
  1315. - u"%s %s (%s)" % (serv.product, serv.version, serv.extrainfo))
  1316. + "%s %s (%s)" % (serv.product, serv.version, serv.extrainfo))
  1317. class ScanDiffSub(ScanDiff):
  1318. @@ -703,7 +703,7 @@ class scan_diff_xml_test(unittest.TestCase):
  1319. a.load_from_file("test-scans/empty.xml")
  1320. b = Scan()
  1321. b.load_from_file("test-scans/simple.xml")
  1322. - f = StringIO.StringIO()
  1323. + f = io.StringIO()
  1324. self.scan_diff = ScanDiffXML(a, b, f)
  1325. self.scan_diff.output()
  1326. self.xml = f.getvalue()
  1327. @@ -712,8 +712,8 @@ class scan_diff_xml_test(unittest.TestCase):
  1328. def test_well_formed(self):
  1329. try:
  1330. document = xml.dom.minidom.parseString(self.xml)
  1331. - except Exception, e:
  1332. - self.fail(u"Parsing XML diff output caused the exception: %s"
  1333. + except Exception as e:
  1334. + self.fail("Parsing XML diff output caused the exception: %s"
  1335. % str(e))
  1336. @@ -739,8 +739,8 @@ def host_apply_diff(host, diff):
  1337. host.os = diff.host_b.os[:]
  1338. if diff.extraports_changed:
  1339. - for state in host.extraports.keys():
  1340. - for port in host.ports.values():
  1341. + for state in list(host.extraports.keys()):
  1342. + for port in list(host.ports.values()):
  1343. if port.state == state:
  1344. del host.ports[port.spec]
  1345. host.extraports = diff.host_b.extraports.copy()
  1346. diff --git a/ndiff/scripts/ndiff b/ndiff/scripts/ndiff
  1347. index 8517c07..4671e73 100755
  1348. --- a/ndiff/scripts/ndiff
  1349. +++ b/ndiff/scripts/ndiff
  1350. @@ -1,4 +1,4 @@
  1351. -#!/usr/bin/env python
  1352. +#!/usr/bin/env python3
  1353. # Ndiff
  1354. #
  1355. @@ -67,15 +67,15 @@ if INSTALL_LIB is not None and is_secure_dir(INSTALL_LIB):
  1356. try:
  1357. import ndiff
  1358. -except ImportError, e:
  1359. - print >> sys.stderr, """\
  1360. +except ImportError as e:
  1361. + print("""\
  1362. Could not import the ndiff module: %s.
  1363. -I checked in these directories:""" % repr(e.message)
  1364. +I checked in these directories:""" % repr(e), file=sys.stderr)
  1365. for dir in sys.path:
  1366. - print >> sys.stderr, " %s" % dir
  1367. - print >> sys.stderr, """\
  1368. + print(" %s" % dir, file=sys.stderr)
  1369. + print("""\
  1370. If you installed Ndiff in another directory, you may have to add the
  1371. -modules directory to the PYTHONPATH environment variable."""
  1372. +modules directory to the PYTHONPATH environment variable.""", file=sys.stderr)
  1373. sys.exit(1)
  1374. import ndiff
  1375. diff --git a/ndiff/setup.py b/ndiff/setup.py
  1376. old mode 100644
  1377. new mode 100755
  1378. index b5e254c..c49bcf3
  1379. --- a/ndiff/setup.py
  1380. +++ b/ndiff/setup.py
  1381. @@ -94,7 +94,7 @@ class checked_install(distutils.command.install.install):
  1382. self.saved_prefix = sys.prefix
  1383. try:
  1384. distutils.command.install.install.finalize_options(self)
  1385. - except distutils.errors.DistutilsPlatformError, e:
  1386. + except distutils.errors.DistutilsPlatformError as e:
  1387. raise distutils.errors.DistutilsPlatformError(str(e) + """
  1388. Installing your distribution's python-dev package may solve this problem.""")
  1389. @@ -155,13 +155,13 @@ Installing your distribution's python-dev package may solve this problem.""")
  1390. #!/usr/bin/env python
  1391. import errno, os, os.path, sys
  1392. -print 'Uninstall %(name)s'
  1393. +print('Uninstall %(name)s')
  1394. answer = raw_input('Are you sure that you want to uninstall '
  1395. '%(name)s (yes/no) ')
  1396. if answer != 'yes' and answer != 'y':
  1397. - print 'Not uninstalling.'
  1398. + print('Not uninstalling.')
  1399. sys.exit(0)
  1400. """ % {'name': APP_NAME}
  1401. @@ -177,8 +177,8 @@ if answer != 'yes' and answer != 'y':
  1402. # This should never happen (everything gets installed
  1403. # inside the root), but if it does, be safe and don't
  1404. # delete anything.
  1405. - uninstaller += ("print '%s was not installed inside "
  1406. - "the root %s; skipping.'\n" % (output, self.root))
  1407. + uninstaller += ("print('%s was not installed inside "
  1408. + "the root %s; skipping.')\n" % (output, self.root))
  1409. continue
  1410. output = path_strip_prefix(output, self.root)
  1411. assert os.path.isabs(output)
  1412. @@ -202,24 +202,24 @@ for path in INSTALLED_FILES:
  1413. dirs.append(path)
  1414. # Delete the files.
  1415. for file in files:
  1416. - print "Removing '%s'." % file
  1417. + print("Removing '%s'." % file)
  1418. try:
  1419. os.remove(file)
  1420. - except OSError, e:
  1421. - print >> sys.stderr, ' Error: %s.' % str(e)
  1422. + except OSError as e:
  1423. + print(' Error: %s.' % str(e), file=sys.stderr)
  1424. # Delete the directories. First reverse-sort the normalized paths by
  1425. # length so that child directories are deleted before their parents.
  1426. dirs = [os.path.normpath(dir) for dir in dirs]
  1427. dirs.sort(key = len, reverse = True)
  1428. for dir in dirs:
  1429. try:
  1430. - print "Removing the directory '%s'." % dir
  1431. + print("Removing the directory '%s'." % dir)
  1432. os.rmdir(dir)
  1433. - except OSError, e:
  1434. + except OSError as e:
  1435. if e.errno == errno.ENOTEMPTY:
  1436. - print "Directory '%s' not empty; not removing." % dir
  1437. + print("Directory '%s' not empty; not removing." % dir)
  1438. else:
  1439. - print >> sys.stderr, str(e)
  1440. + print(str(e), file=sys.stderr)
  1441. """
  1442. uninstaller_file = open(uninstaller_filename, 'w')
  1443. @@ -227,7 +227,7 @@ for dir in dirs:
  1444. uninstaller_file.close()
  1445. # Set exec bit for uninstaller
  1446. - mode = ((os.stat(uninstaller_filename)[ST_MODE]) | 0555) & 07777
  1447. + mode = ((os.stat(uninstaller_filename)[ST_MODE]) | 0o555) & 0o7777
  1448. os.chmod(uninstaller_filename, mode)
  1449. def write_installed_files(self):
  1450. @@ -242,7 +242,7 @@ for dir in dirs:
  1451. try:
  1452. for output in self.get_installed_files():
  1453. assert "\n" not in output
  1454. - print >> f, output
  1455. + print(output, file=f)
  1456. finally:
  1457. f.close()
  1458. @@ -266,7 +266,7 @@ class my_uninstall(distutils.cmd.Command):
  1459. # Read the list of installed files.
  1460. try:
  1461. f = open(INSTALLED_FILES_NAME, "r")
  1462. - except IOError, e:
  1463. + except IOError as e:
  1464. if e.errno == errno.ENOENT:
  1465. log.error("Couldn't open the installation record '%s'. "
  1466. "Have you installed yet?" % INSTALLED_FILES_NAME)
  1467. @@ -289,7 +289,7 @@ class my_uninstall(distutils.cmd.Command):
  1468. try:
  1469. if not self.dry_run:
  1470. os.remove(file)
  1471. - except OSError, e:
  1472. + except OSError as e:
  1473. log.error(str(e))
  1474. # Delete the directories. First reverse-sort the normalized paths by
  1475. # length so that child directories are deleted before their parents.
  1476. @@ -300,7 +300,7 @@ class my_uninstall(distutils.cmd.Command):
  1477. log.info("Removing the directory '%s'." % dir)
  1478. if not self.dry_run:
  1479. os.rmdir(dir)
  1480. - except OSError, e:
  1481. + except OSError as e:
  1482. if e.errno == errno.ENOTEMPTY:
  1483. log.info("Directory '%s' not empty; not removing." % dir)
  1484. else:
  1485. diff --git a/ndiff/test-scans/anonymize.py b/ndiff/test-scans/anonymize.py
  1486. index 9ba612a..fd251fe 100755
  1487. --- a/ndiff/test-scans/anonymize.py
  1488. +++ b/ndiff/test-scans/anonymize.py
  1489. @@ -1,4 +1,4 @@
  1490. -#!/usr/bin/env python
  1491. +#!/usr/bin/env python3
  1492. # Anonymize an Nmap XML file, replacing host name and IP addresses with random
  1493. # anonymous ones. Anonymized names will be consistent between runs of the
  1494. @@ -20,20 +20,20 @@ r = random.Random()
  1495. def hash(s):
  1496. - digest = hashlib.sha512(s).hexdigest()
  1497. + digest = hashlib.sha512(s.encode()).hexdigest()
  1498. return int(digest, 16)
  1499. def anonymize_mac_address(addr):
  1500. r.seed(hash(addr))
  1501. nums = (0, 0, 0) + tuple(r.randrange(256) for i in range(3))
  1502. - return u":".join(u"%02X" % x for x in nums)
  1503. + return ":".join("%02X" % x for x in nums)
  1504. def anonymize_ipv4_address(addr):
  1505. r.seed(hash(addr))
  1506. nums = (10,) + tuple(r.randrange(256) for i in range(3))
  1507. - return u".".join(unicode(x) for x in nums)
  1508. + return ".".join(str(x) for x in nums)
  1509. def anonymize_ipv6_address(addr):
  1510. @@ -41,7 +41,7 @@ def anonymize_ipv6_address(addr):
  1511. # RFC 4193.
  1512. nums = (0xFD00 + r.randrange(256),)
  1513. nums = nums + tuple(r.randrange(65536) for i in range(7))
  1514. - return u":".join("%04X" % x for x in nums)
  1515. + return ":".join("%04X" % x for x in nums)
  1516. # Maps to memoize address and host name conversions.
  1517. hostname_map = {}
  1518. @@ -54,11 +54,11 @@ def anonymize_hostname(name):
  1519. LETTERS = "acbdefghijklmnopqrstuvwxyz"
  1520. r.seed(hash(name))
  1521. length = r.randrange(5, 10)
  1522. - prefix = u"".join(r.sample(LETTERS, length))
  1523. + prefix = "".join(r.sample(LETTERS, length))
  1524. num = r.randrange(1000)
  1525. - hostname_map[name] = u"%s-%d.example.com" % (prefix, num)
  1526. + hostname_map[name] = "%s-%d.example.com" % (prefix, num)
  1527. if VERBOSE:
  1528. - print >> sys.stderr, "Replace %s with %s" % (name, hostname_map[name])
  1529. + print("Replace %s with %s" % (name, hostname_map[name]), file=sys.stderr)
  1530. return hostname_map[name]
  1531. mac_re = re.compile(r'\b([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}\b')
  1532. @@ -78,7 +78,7 @@ def anonymize_address(addr):
  1533. else:
  1534. assert False
  1535. if VERBOSE:
  1536. - print >> sys.stderr, "Replace %s with %s" % (addr, address_map[addr])
  1537. + print("Replace %s with %s" % (addr, address_map[addr]), file=sys.stderr)
  1538. return address_map[addr]