1
0
mirror of https://github.com/nmap/nmap.git synced 2025-12-07 21:21:31 +00:00

Apply PEP 8 style guidance to zenmap

Using the pep8 tool (https://pypi.python.org/pypi/pep8), fixed the
following style issues:

Count   Issue
11      E201 whitespace after '['
8       E203 whitespace before ','
41      E211 whitespace before '('
11      E221 multiple spaces before operator
61      E225 missing whitespace around operator
237     E231 missing whitespace after ':'
91      E251 no spaces around keyword / parameter equals
19      E261 at least two spaces before inline comment
41      E301 expected 1 blank line, found 0
200     E302 expected 2 blank lines, found 1
356     E303 too many blank lines (2)
563     E501 line too long (106 characters)
39      E701 multiple statements on one line (colon)
13      E702 multiple statements on one line (semicolon)
4       W291 trailing whitespace
2       W293 blank line contains whitespace
8       W391 blank line at end of file
21      W601 .has_key() is deprecated, use 'in'
2       W602 deprecated form of raising exception

The remaining issues are long lines due to very deep data structures. I
chose not to alter them, as it would involve backslash-continuation
where whitespace is not permitted:

./zenmapGUI/ScanInterface.py:323:80: E501 line too long (90 characters)
./zenmapGUI/ScanInterface.py:456:80: E501 line too long (84 characters)
./zenmapGUI/ScanInterface.py:464:80: E501 line too long (84 characters)
./zenmapGUI/ScanInterface.py:472:80: E501 line too long (122 characters)
./zenmapGUI/ScanInterface.py:479:80: E501 line too long (122 characters)
./zenmapGUI/ScanInterface.py:920:80: E501 line too long (94 characters)
./zenmapGUI/ScanInterface.py:923:80: E501 line too long (93 characters)
./zenmapGUI/MainWindow.py:575:80: E501 line too long (99 characters)
./zenmapGUI/MainWindow.py:906:80: E501 line too long (99 characters)
This commit is contained in:
dmiller
2014-01-08 19:50:22 +00:00
parent 9210a7f1fa
commit 5c662fffdc
100 changed files with 2287 additions and 1814 deletions

View File

@@ -144,9 +144,10 @@ from zenmapCore.StringPool import unique
# The version of the Nmap DTD this file understands and emits.
XML_OUTPUT_VERSION = "1.04"
class HostInfo(object):
def __init__(self):
self.comment = None;
self.comment = None
self._tcpsequence = {}
self._osmatches = []
self._ports = []
@@ -233,13 +234,14 @@ class HostInfo(object):
"""Return the OS match with the highest accuracy."""
if not self._osmatches:
return None
def osmatch_key(osmatch):
try:
return -float(osmatch["accuracy"])
except ValueError:
return 0
return sorted(self._osmatches, key = osmatch_key)[0]
return sorted(self._osmatches, key=osmatch_key)[0]
# ports_used is a list like
# [{'state': u'open', 'portid': u'22', 'proto': u'tcp'},
@@ -262,7 +264,7 @@ class HostInfo(object):
return self._uptime
# Avoid empty dict return
return {"seconds":"", "lastboot":""}
return {"seconds": "", "lastboot": ""}
# ports is an array containing dicts of the form
# {'port_state': u'open', 'portid': u'22', 'protocol': u'tcp',
@@ -323,14 +325,16 @@ class HostInfo(object):
l.append((1, socket.inet_aton(self.ip["addr"])))
if self.ipv6:
try:
l.append((1, socket.inet_pton(socket.AF_INET6, self.ipv6["addr"])))
l.append((1,
socket.inet_pton(socket.AF_INET6, self.ipv6["addr"])))
except AttributeError:
# Windows doesn't have socket.inet_pton. Go alphabetical.
# Encode to a byte string for possible comparison with binary
# address strings (which can't be converted to unicode).
l.append((1, self.ipv6["addr"].encode("utf-8")))
if self.mac:
l.append((3, "".join([chr(int(x, 16)) for x in self.mac["addr"].split(":")])))
l.append((3, "".join(
chr(int(x, 16)) for x in self.mac["addr"].split(":"))))
l.sort()
return l
@@ -386,7 +390,8 @@ class HostInfo(object):
return self.get_port_count_by_states(('open', 'open|filtered'))
def get_filtered_ports(self):
return self.get_port_count_by_states(('filtered', 'open|filtered', 'closed|filtered'))
return self.get_port_count_by_states(
('filtered', 'open|filtered', 'closed|filtered'))
def get_closed_ports(self):
return self.get_port_count_by_states(('closed', 'closed|filtered'))
@@ -395,7 +400,7 @@ class HostInfo(object):
scanned = 0
for p in self.ports:
scanned+=1
scanned += 1
for extra in self.get_extraports():
scanned += int(extra["count"])
@@ -405,14 +410,16 @@ class HostInfo(object):
def get_services(self):
services = []
for p in self.ports:
services.append({"service_name":p.get("service_name", _("unknown")),
"portid":p.get("portid", ""),
"service_version":p.get("service_version",
_("Unknown version")),
"service_product":p.get("service_product", ""),
"service_extrainfo":p.get("service_extrainfo", ""),
"port_state":p.get("port_state", _("Unknown")),
"protocol":p.get("protocol", "")})
services.append({
"service_name": p.get("service_name", _("unknown")),
"portid": p.get("portid", ""),
"service_version": p.get("service_version",
_("Unknown version")),
"service_product": p.get("service_product", ""),
"service_extrainfo": p.get("service_extrainfo", ""),
"port_state": p.get("port_state", _("Unknown")),
"protocol": p.get("protocol", "")
})
return services
def get_trace(self):
@@ -448,19 +455,22 @@ class HostInfo(object):
services = property(get_services)
trace = property(get_trace, set_trace)
class ParserBasics(object):
def __init__ (self):
def __init__(self):
# This flag informs us whether the XML output file is temporary (True),
# or user specified (False). If any of them is user-specified, it
# doesn't get stripped out of the command string in set_nmap_command.
self.xml_is_temp = True
self.nmap = {'nmaprun':{},\
'scaninfo':[],\
'verbose':'',\
'debugging':'',\
'hosts':[],\
'runstats':{}}
self.nmap = {
'nmaprun': {},
'scaninfo': [],
'verbose': '',
'debugging': '',
'hosts': [],
'runstats': {}
}
self.ops = NmapOptions()
self._nmap_output = None
@@ -490,13 +500,13 @@ class ParserBasics(object):
def set_nmap_output(self, nmap_output):
self._nmap_output = nmap_output
def get_debugging_level (self):
def get_debugging_level(self):
return self.nmap.get('debugging', '')
def set_debugging_level(self, level):
self.nmap['debugging'] = level
def get_verbose_level (self):
def get_verbose_level(self):
return self.nmap.get('verbose', '')
def set_verbose_level(self, level):
@@ -508,7 +518,7 @@ class ParserBasics(object):
def set_scaninfo(self, info):
self.nmap['scaninfo'] = info
def get_services_scanned (self):
def get_services_scanned(self):
if self._services_scanned == None:
return self._services_scanned
@@ -519,10 +529,10 @@ class ParserBasics(object):
self._services_scanned = ','.join(services)
return self._services_scanned
def set_services_scanned (self, services_scanned):
def set_services_scanned(self, services_scanned):
self._services_scanned = services_scanned
def get_nmap_command (self):
def get_nmap_command(self):
return self.ops.render_string()
def set_nmap_command(self, command):
@@ -531,19 +541,19 @@ class ParserBasics(object):
self.ops["-oX"] = None
self.nmap['nmaprun']['args'] = self.ops.render_string()
def get_scan_type (self):
def get_scan_type(self):
types = []
for t in self.nmap.get('scaninfo', []):
types.append(t['type'])
return types
def get_protocol (self):
def get_protocol(self):
protocols = []
for proto in self.nmap.get('scaninfo', []):
protocols.append(proto['protocol'])
return protocols
def get_num_services (self):
def get_num_services(self):
if self._num_services == None:
return self._num_services
@@ -554,12 +564,12 @@ class ParserBasics(object):
self._num_services = num
return self._num_services
def set_num_services (self, num_services):
def set_num_services(self, num_services):
self._num_services = num_services
def get_date (self):
def get_date(self):
epoch = int(self.nmap['nmaprun'].get('start', '0'))
return time.localtime (epoch)
return time.localtime(epoch)
def get_start(self):
return self.nmap['nmaprun'].get('start', '0')
@@ -601,13 +611,13 @@ in epoch format!")
def get_formatted_date(self):
return time.strftime("%B %d, %Y - %H:%M", self.get_date())
def get_scanner (self):
def get_scanner(self):
return self.nmap['nmaprun'].get('scanner', '')
def set_scanner(self, scanner):
self.nmap['nmaprun']['scanner'] = scanner
def get_scanner_version (self):
def get_scanner_version(self):
return self.nmap['nmaprun'].get('version', '')
def set_scanner_version(self, version):
@@ -634,7 +644,7 @@ in epoch format!")
return []
return [host.ipv6 for host in hosts if host.ipv6 is not None]
def get_hostnames (self):
def get_hostnames(self):
hostnames = []
for host in self.nmap.get('hosts', []):
hostnames += host.get_hostnames()
@@ -667,7 +677,7 @@ in epoch format!")
def set_hosts_scanned(self, scanned):
self.nmap['runstats']['hosts_scanned'] = int(scanned)
def get_finish_time (self):
def get_finish_time(self):
return time.localtime(int(self.nmap['runstats'].get('finished_time',
'0')))
@@ -686,7 +696,8 @@ in epoch format!")
if scan_name:
return scan_name
if self.profile_name and self.get_targets():
return _("%s on %s") % (self.profile_name, join_quoted(self.get_targets()))
return _("%s on %s") % (self.profile_name,
join_quoted(self.get_targets()))
return self.get_nmap_command()
def set_scan_name(self, scan_name):
@@ -710,8 +721,8 @@ in epoch format!")
ports[int(item)] = []
ports[int(item)].append(scaninfo['protocol'])
else:
begin,end = item.split('-')
for port in range(int(begin),int(end)+1):
begin, end = item.split('-')
for port in range(int(begin), int(end) + 1):
if int(port) not in ports:
ports[int(port)] = []
ports[int(port)].append(scaninfo['protocol'])
@@ -752,6 +763,7 @@ in epoch format!")
_num_services = None
_services_scanned = None
class NmapParserSAX(ParserBasics, ContentHandler):
def __init__(self):
ParserBasics.__init__(self)
@@ -793,14 +805,15 @@ class NmapParserSAX(ParserBasics, ContentHandler):
def _parse_nmaprun(self, attrs):
run_tag = "nmaprun"
if self._nmap_output is None and attrs.has_key("nmap_output"):
if self._nmap_output is None and "nmap_output" in attrs:
self._nmap_output = attrs["nmap_output"]
self.nmap[run_tag]["profile_name"] = attrs.get("profile_name", "")
self.nmap[run_tag]["start"] = attrs.get("start", "")
self.nmap[run_tag]["args"] = attrs.get("args", "")
self.nmap[run_tag]["scanner"] = attrs.get("scanner", "")
self.nmap[run_tag]["version"] = attrs.get("version", "")
self.nmap[run_tag]["xmloutputversion"] = attrs.get("xmloutputversion", "")
self.nmap[run_tag]["xmloutputversion"] = attrs.get(
"xmloutputversion", "")
self.nmap_command = self.nmap[run_tag]["args"]
@@ -844,9 +857,9 @@ class NmapParserSAX(ParserBasics, ContentHandler):
self.host_info.set_state(unique(attrs.get("state", "")))
def _parse_host_address(self, attrs):
address_attributes = {"type":unique(attrs.get("addrtype", "")),
"vendor":attrs.get("vendor", ""),
"addr":attrs.get("addr", "")}
address_attributes = {"type": unique(attrs.get("addrtype", "")),
"vendor": attrs.get("vendor", ""),
"addr": attrs.get("addr", "")}
if address_attributes["type"] == "ipv4":
self.host_info.set_ip(address_attributes)
@@ -856,16 +869,16 @@ class NmapParserSAX(ParserBasics, ContentHandler):
self.host_info.set_mac(address_attributes)
def _parse_host_hostname(self, attrs):
self.list_hostnames.append({"hostname":attrs.get("name", ""),
"hostname_type":attrs.get("type", "")})
self.list_hostnames.append({"hostname": attrs.get("name", ""),
"hostname_type": attrs.get("type", "")})
def _parse_host_extraports(self, attrs):
self.list_extraports.append({"state":unique(attrs.get("state", "")),
"count":attrs.get("count", "")})
self.list_extraports.append({"state": unique(attrs.get("state", "")),
"count": attrs.get("count", "")})
def _parse_host_port(self, attrs):
self.dic_port = {"protocol":unique(attrs.get("protocol", "")),
"portid":unique(attrs.get("portid", ""))}
self.dic_port = {"protocol": unique(attrs.get("protocol", "")),
"portid": unique(attrs.get("portid", ""))}
def _parse_host_port_state(self, attrs):
self.dic_port["port_state"] = unique(attrs.get("state", ""))
@@ -886,10 +899,12 @@ class NmapParserSAX(ParserBasics, ContentHandler):
self.list_osmatch.append(osmatch)
def _parse_host_portused(self, attrs):
self.list_portused.append(self._parsing(attrs, ['state', 'proto', 'portid'], []))
self.list_portused.append(self._parsing(
attrs, ['state', 'proto', 'portid'], []))
def _parse_host_osclass(self, attrs):
self.list_osclass.append(self._parsing(attrs, ['type', 'vendor', 'osfamily', 'osgen'], ['accuracy']))
self.list_osclass.append(self._parsing(
attrs, ['type', 'vendor', 'osfamily', 'osgen'], ['accuracy']))
def _parsing(self, attrs, unique_names, other_names):
# Returns a dict with the attributes of a given tag with the
@@ -902,17 +917,20 @@ class NmapParserSAX(ParserBasics, ContentHandler):
return dic
def _parse_host_uptime(self, attrs):
self.host_info.set_uptime(self._parsing(attrs, [], ["seconds", "lastboot"]))
self.host_info.set_uptime(self._parsing(
attrs, [], ["seconds", "lastboot"]))
def _parse_host_tcpsequence(self, attrs):
self.host_info.set_tcpsequence(self._parsing(attrs, ['difficulty'], ['index', 'values']))
self.host_info.set_tcpsequence(self._parsing(
attrs, ['difficulty'], ['index', 'values']))
def _parse_host_tcptssequence(self, attrs):
self.host_info.set_tcptssequence(self._parsing(attrs, ['class'], ['values']))
self.host_info.set_tcptssequence(self._parsing(
attrs, ['class'], ['values']))
def _parse_host_ipidsequence(self, attrs):
self.host_info.set_ipidsequence(self._parsing(attrs, ['class'], ['values']))
self.host_info.set_ipidsequence(self._parsing(
attrs, ['class'], ['values']))
def _parse_host_trace(self, attrs):
trace = {}
@@ -1002,7 +1020,6 @@ class NmapParserSAX(ParserBasics, ContentHandler):
elif self.in_host and self.in_trace and name == "error":
self._parse_host_trace_error(attrs)
def endElement(self, name):
if name == "runstats":
self.in_interactive_output = False
@@ -1052,7 +1069,8 @@ class NmapParserSAX(ParserBasics, ContentHandler):
writer = XMLGenerator(f)
writer.startDocument()
if self.xml_stylesheet_data is not None:
writer.processingInstruction("xml-stylesheet", self.xml_stylesheet_data)
writer.processingInstruction(
"xml-stylesheet", self.xml_stylesheet_data)
self._write_nmaprun(writer)
self._write_scaninfo(writer)
self._write_verbose(writer)
@@ -1092,18 +1110,18 @@ class NmapParserSAX(ParserBasics, ContentHandler):
## Finished element
writer.startElement("finished",
Attributes(dict(time = str(self.finish_epoc_time),
timestr = time.ctime(time.mktime(self.get_finish_time())))))
Attributes(dict(time=str(self.finish_epoc_time),
timestr=time.ctime(time.mktime(
self.get_finish_time())))))
writer.endElement("finished")
## Hosts element
writer.startElement("hosts",
Attributes(dict(up = str(self.hosts_up),
down = str(self.hosts_down),
total = str(self.hosts_scanned))))
Attributes(dict(up=str(self.hosts_up),
down=str(self.hosts_down),
total=str(self.hosts_scanned))))
writer.endElement("hosts")
writer.endElement("runstats")
# End of Runstats element
#########################
@@ -1119,7 +1137,6 @@ class NmapParserSAX(ParserBasics, ContentHandler):
Attributes(dict(state=host.state)))
writer.endElement("status")
##################
# Address elements
## IPv4
@@ -1148,15 +1165,14 @@ class NmapParserSAX(ParserBasics, ContentHandler):
# End of Address elements
#########################
###################
# Hostnames element
writer.startElement("hostnames", Attributes({}))
for hname in host.hostnames:
writer.startElement("hostname",
Attributes(dict(name = hname.get("hostname", ""),
type = hname.get("hostname_type", ""))))
Attributes(dict(name=hname.get("hostname", ""),
type=hname.get("hostname_type", ""))))
writer.endElement("hostname")
@@ -1164,7 +1180,6 @@ class NmapParserSAX(ParserBasics, ContentHandler):
# End of Hostnames element
##########################
###############
# Ports element
writer.startElement("ports", Attributes({}))
@@ -1172,15 +1187,15 @@ class NmapParserSAX(ParserBasics, ContentHandler):
## Extraports elements
for ext in host.get_extraports():
writer.startElement("extraports",
Attributes(dict(count = ext.get("count", ""),
state = ext.get("state", ""))))
Attributes(dict(count=ext.get("count", ""),
state=ext.get("state", ""))))
writer.endElement("extraports")
## Port elements
for p in host.ports:
writer.startElement("port",
Attributes(dict(portid = p.get("portid", ""),
protocol = p.get("protocol", ""))))
Attributes(dict(portid=p.get("portid", ""),
protocol=p.get("protocol", ""))))
### Port state
writer.startElement("state",
@@ -1208,7 +1223,6 @@ class NmapParserSAX(ParserBasics, ContentHandler):
# End of Ports element
######################
############
# OS element
writer.startElement("os", Attributes({}))
@@ -1216,25 +1230,25 @@ class NmapParserSAX(ParserBasics, ContentHandler):
## Ports used elements
for pu in host.ports_used:
writer.startElement("portused",
Attributes(dict(state = pu.get("state", ""),
proto = pu.get("proto", ""),
portid = pu.get("portid", ""))))
Attributes(dict(state=pu.get("state", ""),
proto=pu.get("proto", ""),
portid=pu.get("portid", ""))))
writer.endElement("portused")
## Osmatch elements
for om in host.osmatches:
writer.startElement("osmatch",
Attributes(dict(name = om.get("name", ""),
accuracy = om.get("accuracy", ""),
line = om.get("line", ""))))
Attributes(dict(name=om.get("name", ""),
accuracy=om.get("accuracy", ""),
line=om.get("line", ""))))
## Osclass elements
for oc in om['osclasses']:
writer.startElement("osclass",
Attributes(dict(vendor = oc.get("vendor", ""),
osfamily = oc.get("osfamily", ""),
type = oc.get("type", ""),
osgen = oc.get("osgen", ""),
accuracy = oc.get("accuracy", ""))))
Attributes(dict(vendor=oc.get("vendor", ""),
osfamily=oc.get("osfamily", ""),
type=oc.get("type", ""),
osgen=oc.get("osgen", ""),
accuracy=oc.get("accuracy", ""))))
writer.endElement("osclass")
writer.endElement("osmatch")
@@ -1244,8 +1258,8 @@ class NmapParserSAX(ParserBasics, ContentHandler):
# Uptime element
writer.startElement("uptime",
Attributes(dict(seconds = host.uptime.get("seconds", ""),
lastboot = host.uptime.get("lastboot", ""))))
Attributes(dict(seconds=host.uptime.get("seconds", ""),
lastboot=host.uptime.get("lastboot", ""))))
writer.endElement("uptime")
#####################
@@ -1253,21 +1267,21 @@ class NmapParserSAX(ParserBasics, ContentHandler):
## TCP Sequence element
# Cannot use dict() here, because of the 'class' attribute.
writer.startElement("tcpsequence",
Attributes({"index":host.tcpsequence.get("index", ""),
"difficulty":host.tcpsequence.get("difficulty", ""),
"values":host.tcpsequence.get("values", "")}))
Attributes({"index": host.tcpsequence.get("index", ""),
"difficulty": host.tcpsequence.get("difficulty", ""),
"values": host.tcpsequence.get("values", "")}))
writer.endElement("tcpsequence")
## IP ID Sequence element
writer.startElement("ipidsequence",
Attributes({"class":host.ipidsequence.get("class", ""),
"values":host.ipidsequence.get("values", "")}))
Attributes({"class": host.ipidsequence.get("class", ""),
"values": host.ipidsequence.get("values", "")}))
writer.endElement("ipidsequence")
## TCP TS Sequence element
writer.startElement("tcptssequence",
Attributes({"class":host.tcptssequence.get("class", ""),
"values":host.tcptssequence.get("values", "")}))
Attributes({"class": host.tcptssequence.get("class", ""),
"values": host.tcptssequence.get("values", "")}))
writer.endElement("tcptssequence")
# End of sequences elements
###########################
@@ -1275,21 +1289,21 @@ class NmapParserSAX(ParserBasics, ContentHandler):
## Trace element
if len(host.trace) > 0:
writer.startElement("trace",
Attributes({"proto":host.trace.get("proto", ""),
"port":host.trace.get("port", "")}))
Attributes({"proto": host.trace.get("proto", ""),
"port": host.trace.get("port", "")}))
if "hops" in host.trace:
for hop in host.trace["hops"]:
writer.startElement("hop",
Attributes({"ttl":hop["ttl"],
"rtt":hop["rtt"],
"ipaddr":hop["ipaddr"],
"host":hop["host"]}))
Attributes({"ttl": hop["ttl"],
"rtt": hop["rtt"],
"ipaddr": hop["ipaddr"],
"host": hop["host"]}))
writer.endElement("hop")
if "error" in host.trace:
writer.startElement("error",
Attributes({"errorstr":host.trace["error"]}))
Attributes({"errorstr": host.trace["error"]}))
writer.endElement("error")
writer.endElement("trace")
@@ -1312,21 +1326,22 @@ class NmapParserSAX(ParserBasics, ContentHandler):
def _write_scaninfo(self, writer):
for scan in self.scaninfo:
writer.startElement("scaninfo",
Attributes(dict(type = scan.get("type", ""),
protocol = scan.get("protocol", ""),
numservices = scan.get("numservices", ""),
services = scan.get("services", ""))))
Attributes(dict(type=scan.get("type", ""),
protocol=scan.get("protocol", ""),
numservices=scan.get("numservices", ""),
services=scan.get("services", ""))))
writer.endElement("scaninfo")
def _write_nmaprun(self, writer):
writer.startElement("nmaprun",
Attributes(dict(args = str(self.nmap_command),
profile_name = str(self.profile_name),
scanner = str(self.scanner),
start = str(self.start),
startstr = time.ctime(time.mktime(self.get_date())),
version = str(self.scanner_version),
xmloutputversion = str(XML_OUTPUT_VERSION))))
Attributes(dict(args=str(self.nmap_command),
profile_name=str(self.profile_name),
scanner=str(self.scanner),
start=str(self.start),
startstr=time.ctime(
time.mktime(self.get_date())),
version=str(self.scanner_version),
xmloutputversion=str(XML_OUTPUT_VERSION))))
def set_unsaved(self):
self.unsaved = True
@@ -1334,6 +1349,7 @@ class NmapParserSAX(ParserBasics, ContentHandler):
def is_unsaved(self):
return self.unsaved
def nmap_parser_sax():
parser = make_parser()
nmap_parser = NmapParserSAX()
@@ -1345,6 +1361,7 @@ def nmap_parser_sax():
NmapParser = nmap_parser_sax
if __name__ == '__main__':
import sys