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.

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