Merge #2088: Update Zenmap to Python 3 and PyGObject

Note: Ndiff build will be broken until subsequent changes are made.
Deprecation warnings will need to be addressed in future changes.
Closes #2088
This commit is contained in:
dmiller 2022-12-07 20:34:03 +00:00
parent e2e55660c3
commit 24b26317c7
104 changed files with 5381 additions and 4383 deletions

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -65,7 +64,7 @@ import sys
from zenmapCore.Name import APP_NAME
def fs_dec(s):
def fs_dec(s): # This is unused now
"""Decode s from the filesystem decoding, handling various possible
errors."""
enc = sys.getfilesystemencoding()
@ -88,7 +87,7 @@ def fs_enc(u):
# systems like Windows where the file system encoding is different from the
# result of sys.getdefaultencoding(). So we call os.path.expanduser with a
# plain string and decode it from the filesystem encoding.
HOME = fs_dec(os.path.expanduser("~"))
HOME = os.path.expanduser("~")
# The base_paths dict in this file gives symbolic names to various files. For
# example, use base_paths.target_list instead of 'target_list.txt'.

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -103,10 +102,10 @@ def install_gettext(locale_dir):
else:
t = gettext.translation(
APP_NAME, locale_dir, languages=get_locales(), fallback=True)
t.install(unicode=True)
t.install()
# Install a dummy _ function so modules can safely use it after importing this
# module, even if they don't install the gettext version.
import __builtin__
__builtin__.__dict__["_"] = lambda s: s
import builtins
builtins.__dict__["_"] = lambda s: s

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -69,7 +68,7 @@ APP_DOWNLOAD_SITE = "https://nmap.org/download.html"
APP_DOCUMENTATION_SITE = "https://nmap.org/book/zenmap.html"
APP_COPYRIGHT = "Copyright 2005-2022 Nmap Software LLC"
NMAP_DISPLAY_NAME = u"Nmap"
NMAP_DISPLAY_NAME = "Nmap"
NMAP_WEB_SITE = "https://nmap.org"
UMIT_DISPLAY_NAME = "Umit"

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -63,7 +62,7 @@ import unittest
import zenmapCore
import zenmapCore.NmapParser
from zenmapGUI.SearchGUI import SearchParser
from SearchResult import HostSearch
from .SearchResult import HostSearch
class NetworkInventory(object):
@ -255,13 +254,13 @@ class NetworkInventory(object):
return self.scans
def get_hosts(self):
return self.hosts.values()
return list(self.hosts.values())
def get_hosts_up(self):
return filter(lambda h: h.get_state() == 'up', self.hosts.values())
return [h for h in list(self.hosts.values()) if h.get_state() == 'up']
def get_hosts_down(self):
return filter(lambda h: h.get_state() == 'down', self.hosts.values())
return [h for h in list(self.hosts.values()) if h.get_state() == 'down']
def open_from_file(self, path):
"""Loads a scan from the given file."""
@ -353,7 +352,7 @@ class NetworkInventory(object):
a list of (full-path) filenames that were used to save the scans."""
self._generate_filenames(path)
for scan, filename in self.filenames.iteritems():
for scan, filename in self.filenames.items():
f = open(os.path.join(path, filename), "w")
scan.write_xml(f)
f.close()
@ -367,7 +366,7 @@ class NetworkInventory(object):
# For now, this saves each scan making up the inventory separately in
# the database.
from time import time
from cStringIO import StringIO
from io import StringIO
from zenmapCore.UmitDB import Scans
for parsed in self.get_scans():
@ -424,15 +423,13 @@ class FilteredNetworkInventory(NetworkInventory):
def get_hosts_up(self):
if len(self.search_dict) > 0:
return filter(lambda h: h.get_state() == 'up',
self.filtered_hosts)
return [h for h in self.filtered_hosts if h.get_state() == 'up']
else:
return NetworkInventory.get_hosts_up(self)
def get_hosts_down(self):
if len(self.search_dict) > 0:
return filter(lambda h: h.get_state() == 'down',
self.filtered_hosts)
return [h for h in self.filtered_hosts if h.get_state() == 'down']
else:
return NetworkInventory.get_hosts_down(self)
@ -508,10 +505,10 @@ class FilteredNetworkInventory(NetworkInventory):
self.filter_text = filter_text.lower()
self.search_parser.update(self.filter_text)
self.filtered_hosts = []
for hostname, host in self.hosts.iteritems():
for hostname, host in self.hosts.items():
# For each host in this scan
# Test each given operator against the current host
for operator, args in self.search_dict.iteritems():
for operator, args in self.search_dict.items():
if not self._match_all_args(host, operator, args):
# No match => we discard this scan_result
break
@ -582,7 +579,7 @@ class NetworkInventoryTest(unittest.TestCase):
inv.remove_scan(scan_3)
except Exception:
pass
self.assertEqual(added_ips, inv.hosts.keys())
self.assertEqual(added_ips, list(inv.hosts.keys()))
self.assertEqual(host_a.hostnames, ["a"])
self.assertEqual(host_b.hostnames, ["b"])
@ -646,7 +643,7 @@ if __name__ == "__main__":
inventory1.add_scan(scan2)
for host in inventory1.get_hosts():
print "%s" % host.ip["addr"],
print("%s" % host.ip["addr"], end=' ')
#if len(host.hostnames) > 0:
# print "[%s]:" % host.hostnames[0]["hostname"]
#else:
@ -662,12 +659,12 @@ if __name__ == "__main__":
inventory1.remove_scan(scan2)
print
for host in inventory1.get_hosts():
print "%s" % host.ip["addr"],
print("%s" % host.ip["addr"], end=' ')
inventory1.add_scan(scan2)
print
for host in inventory1.get_hosts():
print "%s" % host.ip["addr"],
print("%s" % host.ip["addr"], end=' ')
dir = "/home/ndwi/scanz/top01"
inventory1.save_to_dir(dir)
@ -675,6 +672,6 @@ if __name__ == "__main__":
inventory2 = NetworkInventory()
inventory2.open_from_dir(dir)
print
print()
for host in inventory2.get_hosts():
print "%s" % host.ip["addr"],
print("%s" % host.ip["addr"], end=' ')

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -73,7 +72,7 @@ import zenmapCore.I18N # lgtm[py/unused-import]
try:
import subprocess
except ImportError, e:
except ImportError as e:
raise ImportError(str(e) + ".\n" + _("Python 2.4 or later is required."))
import zenmapCore.Paths
@ -183,7 +182,7 @@ class NmapCommand(object):
if self.xml_is_temp:
try:
os.remove(self.xml_output_filename)
except OSError, e:
except OSError as e:
if e.errno != errno.ENOENT:
raise

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# This is an Nmap command line parser. It has two main parts:
#
@ -539,7 +539,7 @@ class NmapOptions(object):
return self.d.setdefault(self.canonicalize_name(key), default)
def handle_result(self, result):
if isinstance(result, basestring):
if isinstance(result, str):
# A positional argument.
self.target_specs.append(result)
return
@ -640,7 +640,7 @@ class NmapOptions(object):
self["-d"] = int(arg)
except ValueError:
if reduce(lambda x, y: x and y,
map(lambda z: z == "d", arg), True):
[z == "d" for z in arg], True):
self.setdefault("-d", 0)
self["-d"] += len(arg) + 1
else:
@ -720,7 +720,7 @@ class NmapOptions(object):
self["-v"] = -1
except ValueError:
if reduce(lambda x, y: x and y,
map(lambda z: z == "v", arg), True):
[z == "v" for z in arg], True):
self.setdefault("-v", 0)
self["-v"] += len(arg) + 1
else:
@ -763,7 +763,7 @@ class NmapOptions(object):
opt_list.append("-T%s" % str(self["-T"]))
if self["-O"] is not None:
if isinstance(self["-O"], basestring):
if isinstance(self["-O"], str):
opt_list.append("-O%s" % self["-O"])
elif self["-O"]:
opt_list.append("-O")
@ -815,7 +815,7 @@ class NmapOptions(object):
if self[ping_option] is not None:
opt_list.append(ping_option + self[ping_option])
if self["-PB"] is not None:
if isinstance(self["-PB"], basestring):
if isinstance(self["-PB"], str):
opt_list.append("-PB" + self["-PB"])
elif self["-PB"]:
opt_list.append("-PB")

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -63,11 +62,7 @@ import time
import socket
import copy
# Use the faster cStringIO if available, fallback on StringIO if not
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from io import StringIO
# Prevent loading PyXML
import xml
@ -558,12 +553,7 @@ in epoch format!")
return ports
def get_formatted_date(self):
try:
return time.strftime("%B %d, %Y - %H:%M", self.get_date()).decode(
locale.getpreferredencoding())
except LookupError:
# encoding or locale not found
return time.asctime(self.get_date()).decode('ascii')
return time.strftime("%B %d, %Y - %H:%M", self.get_date())
def get_scanner(self):
return self.nmap['nmaprun'].get('scanner', '')
@ -1333,25 +1323,25 @@ if __name__ == '__main__':
np.parse_file(file_to_parse)
for host in np.hosts:
print "%s:" % host.ip["addr"]
print " Comment:", repr(host.comment)
print " TCP sequence:", repr(host.tcpsequence)
print " TCP TS sequence:", repr(host.tcptssequence)
print " IP ID sequence:", repr(host.ipidsequence)
print " Uptime:", repr(host.uptime)
print " OS Match:", repr(host.osmatches)
print " Ports:"
print("%s:" % host.ip["addr"])
print(" Comment:", repr(host.comment))
print(" TCP sequence:", repr(host.tcpsequence))
print(" TCP TS sequence:", repr(host.tcptssequence))
print(" IP ID sequence:", repr(host.ipidsequence))
print(" Uptime:", repr(host.uptime))
print(" OS Match:", repr(host.osmatches))
print(" Ports:")
for p in host.ports:
print "\t%s" % repr(p)
print " Ports used:", repr(host.ports_used)
print " OS Matches:", repr(host.osmatches)
print " Hostnames:", repr(host.hostnames)
print " IP:", repr(host.ip)
print " IPv6:", repr(host.ipv6)
print " MAC:", repr(host.mac)
print " State:", repr(host.state)
print("\t%s" % repr(p))
print(" Ports used:", repr(host.ports_used))
print(" OS Matches:", repr(host.osmatches))
print(" Hostnames:", repr(host.hostnames))
print(" IP:", repr(host.ip))
print(" IPv6:", repr(host.ipv6))
print(" MAC:", repr(host.mac))
print(" State:", repr(host.state))
if "hops" in host.trace:
print " Trace:"
print(" Trace:")
for hop in host.trace["hops"]:
print " ", repr(hop)
print
print(" ", repr(hop))
print()

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -66,7 +65,7 @@ import os.path
import sys
import shutil
from zenmapCore.BasePaths import base_paths, fs_dec
from zenmapCore.BasePaths import base_paths
from zenmapCore.Name import APP_NAME
@ -79,14 +78,14 @@ def get_prefix():
frozen = getattr(sys, "frozen", None)
if frozen == "macosx_app" or "Zenmap.app" in sys.executable:
# A py2app .app bundle.
return os.path.join(dirname(fs_dec(sys.executable)), "..", "Resources")
return os.path.join(dirname(sys.executable), "..", "Resources")
elif frozen is not None:
# Assume a py2exe executable.
return dirname(fs_dec(sys.executable))
return dirname(sys.executable)
else:
# Normal script execution. Look in the current directory to allow
# running from the distribution.
return os.path.abspath(os.path.dirname(fs_dec(sys.argv[0])))
return os.path.abspath(os.path.dirname(sys.argv[0]))
prefix = get_prefix()
@ -182,7 +181,7 @@ def create_dir(path):
directory already exists."""
try:
os.makedirs(path)
except OSError, e:
except OSError as e:
if e.errno != errno.EEXIST:
raise
@ -224,19 +223,19 @@ def return_if_exists(path, create=False):
Path = Paths()
if __name__ == '__main__':
print ">>> SAVED DIRECTORIES:"
print ">>> LOCALE DIR:", Path.locale_dir
print ">>> PIXMAPS DIR:", Path.pixmaps_dir
print ">>> CONFIG DIR:", Path.config_dir
print
print ">>> FILES:"
print ">>> USER CONFIG FILE:", Path.user_config_file
print ">>> CONFIG FILE:", Path.user_config_file
print ">>> TARGET_LIST:", Path.target_list
print ">>> PROFILE_EDITOR:", Path.profile_editor
print ">>> SCAN_PROFILE:", Path.scan_profile
print ">>> RECENT_SCANS:", Path.recent_scans
print ">>> OPTIONS:", Path.options
print
print ">>> DB:", Path.db
print ">>> VERSION:", Path.version
print(">>> SAVED DIRECTORIES:")
print(">>> LOCALE DIR:", Path.locale_dir)
print(">>> PIXMAPS DIR:", Path.pixmaps_dir)
print(">>> CONFIG DIR:", Path.config_dir)
print()
print(">>> FILES:")
print(">>> USER CONFIG FILE:", Path.user_config_file)
print(">>> CONFIG FILE:", Path.user_config_file)
print(">>> TARGET_LIST:", Path.target_list)
print(">>> PROFILE_EDITOR:", Path.profile_editor)
print(">>> SCAN_PROFILE:", Path.scan_profile)
print(">>> RECENT_SCANS:", Path.recent_scans)
print(">>> OPTIONS:", Path.options)
print()
print(">>> DB:", Path.db)
print(">>> VERSION:", Path.version)

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -113,7 +112,7 @@ recent_scans = RecentScans()
if __name__ == "__main__":
r = RecentScans()
print ">>> Getting empty list:", r.get_recent_scans_list()
print ">>> Adding recent scan bla:", r.add_recent_scan("bla")
print ">>> Getting recent scan list:", r.get_recent_scans_list()
print(">>> Getting empty list:", r.get_recent_scans_list())
print(">>> Adding recent scan bla:", r.add_recent_scan("bla"))
print(">>> Getting recent scan list:", r.get_recent_scans_list())
del r

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -188,21 +188,21 @@ if __name__ == '__main__':
for test, expected in TESTS:
args_dict = parse_script_args_dict(test)
print args_dict
print(args_dict)
args = parse_script_args(test)
if args == expected:
print "PASS", test
print("PASS", test)
continue
print "FAIL", test
print("FAIL", test)
if args is None:
print "Parsing error"
print("Parsing error")
else:
print "%d args" % len(args)
print("%d args" % len(args))
for a, v in args:
print a, "=", v
print(a, "=", v)
if expected is None:
print "Expected parsing error"
print("Expected parsing error")
else:
print "Expected %d args" % len(expected)
print("Expected %d args" % len(expected))
for a, v in expected:
print a, "=", v
print(a, "=", v)

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -438,16 +438,16 @@ def get_script_entries(scripts_dir, nselib_dir):
if __name__ == '__main__':
import sys
for entry in get_script_entries(sys.argv[1], sys.argv[2]):
print "*" * 75
print "Filename:", entry.filename
print "Categories:", entry.categories
print "License:", entry.license
print "Author:", entry.author
print "URL:", entry.url
print "Description:", entry.description
print "Arguments:", [x[0] for x in entry.arguments]
print "Output:"
print entry.output
print "Usage:"
print entry.usage
print "*" * 75
print("*" * 75)
print("Filename:", entry.filename)
print("Categories:", entry.categories)
print("License:", entry.license)
print("Author:", entry.author)
print("URL:", entry.url)
print("Description:", entry.description)
print("Arguments:", [x[0] for x in entry.arguments])
print("Output:")
print(entry.output)
print("Usage:")
print(entry.usage)
print("*" * 75)

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -61,11 +60,10 @@
import os
import os.path
import re
import StringIO
import io
import unittest
from glob import glob
from types import StringTypes
from zenmapCore.Name import APP_NAME
from zenmapCore.NmapOptions import NmapOptions
@ -170,7 +168,7 @@ class SearchResult(object):
self.parsed_scan = scan_result
# Test each given operator against the current parsed result
for operator, args in kargs.iteritems():
for operator, args in kargs.items():
if not self._match_all_args(operator, args):
# No match => we discard this scan_result
break
@ -319,7 +317,7 @@ class SearchResult(object):
return True
# Transform a comma-delimited string containing ports into a list
ports = filter(lambda not_empty: not_empty, ports.split(","))
ports = [not_empty for not_empty in ports.split(",") if not_empty]
# Check if they're parsable, if not return False silently
for port in ports:
@ -356,7 +354,7 @@ class SearchResult(object):
log.debug("Match port:%s" % ports)
# Transform a comma-delimited string containing ports into a list
ports = filter(lambda not_empty: not_empty, ports.split(","))
ports = [not_empty for not_empty in ports.split(",") if not_empty]
for host in self.parsed_scan.get_hosts():
for port in ports:
@ -442,11 +440,11 @@ class SearchDB(SearchResult, object):
log.debug(">>> Nmap xml output: %s" % scan.nmap_xml_output)
try:
buffer = StringIO.StringIO(scan.nmap_xml_output)
buffer = io.StringIO(scan.nmap_xml_output)
parsed = NmapParser()
parsed.parse(buffer)
buffer.close()
except Exception, e:
except Exception as e:
log.warning(">>> Error loading scan with ID %u from database: "
"%s" % (scan.scans_id, str(e)))
else:
@ -462,7 +460,7 @@ class SearchDir(SearchResult, object):
log.debug(">>> SearchDir initialized")
self.search_directory = search_directory
if isinstance(file_extensions, StringTypes):
if isinstance(file_extensions, str):
self.file_extensions = file_extensions.split(";")
elif isinstance(file_extensions, list):
self.file_extensions = file_extensions

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -114,7 +113,7 @@ target_list = TargetList()
if __name__ == "__main__":
t = TargetList()
print ">>> Getting empty list:", t.get_target_list()
print ">>> Adding target 127.0.0.1:", t.add_target("127.0.0.3")
print ">>> Getting target list:", t.get_target_list()
print(">>> Getting empty list:", t.get_target_list())
print(">>> Adding target 127.0.0.1:", t.add_target("127.0.0.3"))
print(">>> Getting target list:", t.get_target_list())
del t

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -60,9 +59,8 @@
import re
from types import StringTypes
from ConfigParser import DuplicateSectionError, NoSectionError, NoOptionError
from ConfigParser import Error as ConfigParser_Error
from configparser import DuplicateSectionError, NoSectionError, NoOptionError
from configparser import Error as ConfigParser_Error
from zenmapCore.Paths import Path
from zenmapCore.UmitLogging import log
@ -107,7 +105,7 @@ class SearchConfig(UmitConfigParser, object):
self.search_db = True
def _get_it(self, p_name, default):
return config_parser.get(self.section_name, p_name, default)
return config_parser.get(self.section_name, p_name, fallback=default)
def _set_it(self, p_name, value):
config_parser.set(self.section_name, p_name, value)
@ -117,10 +115,8 @@ class SearchConfig(UmitConfigParser, object):
attr == "True" or \
attr == "true" or \
attr == "1":
return 1
return 0
return "True"
return "False"
def get_directory(self):
return self._get_it("directory", "")
@ -134,7 +130,7 @@ class SearchConfig(UmitConfigParser, object):
def set_file_extension(self, file_extension):
if isinstance(file_extension, list):
self._set_it("file_extension", ";".join(file_extension))
elif isinstance(file_extension, StringTypes):
elif isinstance(file_extension, str):
self._set_it("file_extension", file_extension)
def get_save_time(self):
@ -143,7 +139,7 @@ class SearchConfig(UmitConfigParser, object):
def set_save_time(self, save_time):
if isinstance(save_time, list):
self._set_it("save_time", ";".join(save_time))
elif isinstance(save_time, StringTypes):
elif isinstance(save_time, str):
self._set_it("save_time", save_time)
def get_store_results(self):
@ -272,7 +268,7 @@ class WindowConfig(UmitConfigParser, object):
self.height = self.default_height
def _get_it(self, p_name, default):
return config_parser.get(self.section_name, p_name, default)
return config_parser.get(self.section_name, p_name, fallback=default)
def _set_it(self, p_name, value):
config_parser.set(self.section_name, p_name, value)
@ -401,7 +397,7 @@ class NmapOutputHighlight(object):
try:
return self.sanity_settings([
config_parser.get(
property_name, prop, True) for prop in self.setts])
property_name, prop, raw=True) for prop in self.setts])
except Exception:
settings = []
prop_settings = self.default_highlights[p_name]
@ -420,7 +416,7 @@ class NmapOutputHighlight(object):
property_name = "%s_highlight" % property_name
settings = self.sanity_settings(list(settings))
for pos in xrange(len(settings)):
for pos in range(len(settings)):
config_parser.set(property_name, self.setts[pos], settings[pos])
def sanity_settings(self, settings):
@ -437,13 +433,13 @@ class NmapOutputHighlight(object):
settings[1] = self.boolean_sanity(settings[1])
settings[2] = self.boolean_sanity(settings[2])
tuple_regex = "[\(\[]\s?(\d+)\s?,\s?(\d+)\s?,\s?(\d+)\s?[\)\]]"
if isinstance(settings[3], basestring):
tuple_regex = r"[\(\[]\s?(\d+)\s?,\s?(\d+)\s?,\s?(\d+)\s?[\)\]]"
if isinstance(settings[3], str):
settings[3] = [
int(t) for t in re.findall(tuple_regex, settings[3])[0]
]
if isinstance(settings[4], basestring):
if isinstance(settings[4], str):
settings[4] = [
int(h) for h in re.findall(tuple_regex, settings[4])[0]
]
@ -542,57 +538,57 @@ class NmapOutputHighlight(object):
"underline": str(False),
"text": [0, 0, 0],
"highlight": [65535, 65535, 65535],
"regex": "\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}\s.{1,4}"},
"regex": r"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}\s.{1,4}"},
"hostname": {
"bold": str(True),
"italic": str(True),
"underline": str(True),
"text": [0, 111, 65535],
"highlight": [65535, 65535, 65535],
"regex": "(\w{2,}://)*[\w-]{2,}\.[\w-]{2,}"
"(\.[\w-]{2,})*(/[[\w-]{2,}]*)*"},
"regex": r"(\w{2,}://)*[\w-]{2,}\.[\w-]{2,}"
r"(\.[\w-]{2,})*(/[[\w-]{2,}]*)*"},
"ip": {
"bold": str(True),
"italic": str(False),
"underline": str(False),
"text": [0, 0, 0],
"highlight": [65535, 65535, 65535],
"regex": "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"},
"regex": r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"},
"port_list": {
"bold": str(True),
"italic": str(False),
"underline": str(False),
"text": [0, 1272, 28362],
"highlight": [65535, 65535, 65535],
"regex": "PORT\s+STATE\s+SERVICE(\s+VERSION)?[^\n]*"},
"regex": r"PORT\s+STATE\s+SERVICE(\s+VERSION)?[^\n]*"},
"open_port": {
"bold": str(True),
"italic": str(False),
"underline": str(False),
"text": [0, 41036, 2396],
"highlight": [65535, 65535, 65535],
"regex": "\d{1,5}/.{1,5}\s+open\s+.*"},
"regex": r"\d{1,5}/.{1,5}\s+open\s+.*"},
"closed_port": {
"bold": str(False),
"italic": str(False),
"underline": str(False),
"text": [65535, 0, 0],
"highlight": [65535, 65535, 65535],
"regex": "\d{1,5}/.{1,5}\s+closed\s+.*"},
"regex": r"\d{1,5}/.{1,5}\s+closed\s+.*"},
"filtered_port": {
"bold": str(False),
"italic": str(False),
"underline": str(False),
"text": [38502, 39119, 0],
"highlight": [65535, 65535, 65535],
"regex": "\d{1,5}/.{1,5}\s+filtered\s+.*"},
"regex": r"\d{1,5}/.{1,5}\s+filtered\s+.*"},
"details": {
"bold": str(True),
"italic": str(False),
"underline": str(True),
"text": [0, 0, 0],
"highlight": [65535, 65535, 65535],
"regex": "^(\w{2,}[\s]{,3}){,4}:"}
"regex": r"^(\w{2,}[\s]{,3}){,4}:"}
}

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -58,7 +57,7 @@
# * *
# ***************************************************************************/
from ConfigParser import ConfigParser, DEFAULTSECT, NoOptionError, \
from configparser import ConfigParser, DEFAULTSECT, NoOptionError, \
NoSectionError
from zenmapCore.UmitLogging import log
@ -74,7 +73,7 @@ class UmitConfigParser(ConfigParser):
if not self.has_section(section):
self.add_section(section)
ConfigParser.set(self, section, option, value)
ConfigParser.set(self, section, option, str(value))
self.save_changes()
def read(self, filename):
@ -104,15 +103,13 @@ class UmitConfigParser(ConfigParser):
if self._defaults:
fp.write("[%s]\n" % DEFAULTSECT)
items = self._defaults.items()
items.sort()
items = sorted(self._defaults.items())
for (key, value) in items:
fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
fp.write("\n")
sects = self._sections.keys()
sects.sort()
sects = sorted(self._sections.keys())
for section in sects:
fp.write("[%s]\n" % section)

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
@ -58,20 +57,10 @@
# * *
# ***************************************************************************/
import sqlite3
import sys
from hashlib import md5
sqlite = None
try:
from pysqlite2 import dbapi2 as sqlite
except ImportError:
try:
# In case this script is been running under python2.5 with sqlite3
import sqlite3 as sqlite
except ImportError:
raise ImportError(_("No module named dbapi2.pysqlite2 or sqlite3"))
from time import time
from zenmapCore.Paths import Path
@ -84,7 +73,7 @@ try:
umitdb = Path.db
except Exception:
import os.path
from BasePaths import base_paths
from .BasePaths import base_paths
umitdb = os.path.join(Path.user_config_dir, base_paths["db"])
Path.db = umitdb
@ -102,28 +91,7 @@ if not exists(umitdb) or \
umitdb = ":memory:"
using_memory = True
if isinstance(umitdb, str):
fs_enc = sys.getfilesystemencoding()
if fs_enc is None:
fs_enc = "UTF-8"
umitdb = umitdb.decode(fs_enc)
# pysqlite 2.4.0 doesn't handle a unicode database name, though earlier and
# later versions do. Encode to UTF-8 as pysqlite would do internally anyway.
umitdb = umitdb.encode("UTF-8")
connection = sqlite.connect(umitdb)
# By default pysqlite will raise an OperationalError when trying to return a
# TEXT data type that is not UTF-8 (it always tries to decode text in order to
# return a unicode object). We store XML in the database, which may have a
# different encoding, so instruct pysqlite to return a plain str for TEXT data
# types, and not to attempt any decoding.
try:
connection.text_factory = str
except AttributeError:
# However, text_factory is available only in pysqlite 2.1.0 and later.
pass
connection = sqlite3.connect(umitdb)
class Table(object):
@ -170,7 +138,7 @@ class Table(object):
sql = sql[:][:-2]
sql += ") VALUES ("
for v in xrange(len(kargs.values())):
for v in range(len(kargs.values())):
sql += "?, "
sql = sql[:][:-2]
@ -258,7 +226,7 @@ class Scans(Table, object):
raise Exception("Can't save result without xml output")
if not self.verify_digest(
md5(kargs["nmap_xml_output"]).hexdigest()):
md5(kargs["nmap_xml_output"].encode("UTF-8")).hexdigest()):
raise Exception("XML output registered already!")
self.scans_id = self.insert(**kargs)
@ -302,7 +270,7 @@ class Scans(Table, object):
def set_nmap_xml_output(self, nmap_xml_output):
self.set_item("nmap_xml_output", nmap_xml_output)
self.set_item("digest", md5(nmap_xml_output).hexdigest())
self.set_item("digest", md5(nmap_xml_output.encode("UTF-8")).hexdigest())
def get_date(self):
return self.get_item("date")
@ -328,7 +296,7 @@ def verify_db():
cursor = connection.cursor()
try:
cursor.execute("SELECT scans_id FROM scans WHERE date = 0")
except sqlite.OperationalError:
except sqlite3.OperationalError:
u = UmitDB()
u.create_db()
verify_db()
@ -354,5 +322,5 @@ if __name__ == "__main__":
sql = "SELECT * FROM scans;"
u.cursor.execute(sql)
print "Scans:",
print("Scans:", end=' ')
pprint(u.cursor.fetchall())

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *

View file

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *