Skip to content

Commit 2913edb

Browse files
committed
pep8 and pyflakesed. FIXME: pylint me
1 parent b31a150 commit 2913edb

9 files changed

Lines changed: 228 additions & 129 deletions

File tree

libnmap/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
__author__ = 'Ronald Bister, Mike Boutillier'
2-
__credits__ = [ 'Ronald Bister', 'Mike Boutillier' ]
2+
__credits__ = ['Ronald Bister', 'Mike Boutillier']
33
__maintainer__ = 'Ronald Bister'
4-
__email__ = 'mini.pelle@gmail.com'
4+
__email__ = 'mini.pelle@gmail.com'
55
__license__ = 'CC-BY'
66
__version__ = '0.1'
7-
__all__ = [ "NmapHost", "NmapService", "NmapParser", "NmapParserException",
8-
"NmapReport", "NmapProcess", "DictDiffer", "NmapDiff",
9-
"NmapDiffException", "ReportDecoder", "ReportDecoder" ]
7+
__all__ = ["NmapHost", "NmapService", "NmapParser", "NmapParserException",
8+
"NmapReport", "NmapProcess", "DictDiffer", "NmapDiff",
9+
"NmapDiffException", "ReportDecoder", "ReportEncoder"]
1010

1111
from diff import NmapDiff, DictDiffer, NmapDiffException
1212
from common import NmapHost, NmapService

libnmap/common.py

Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
#!/usr/bin/env python
2-
from libnmap import NmapDiff, NmapDiffException
2+
from libnmap import NmapDiff
3+
34

45
class NmapHost(object):
5-
def __init__(self, starttime='', endtime='', address=None, status=None,
6+
def __init__(self, starttime='', endtime='', address=None, status=None,
67
hostnames=None, services=None):
78
self._starttime = starttime
89
self._endtime = endtime
@@ -16,17 +17,19 @@ def __eq__(self, other):
1617
self.address == other.address and self.changed(other) == 0)
1718

1819
def __ne__(self, other):
19-
return ((self._hostnames != other._hostnames or
20+
return ((self._hostnames != other._hostnames or
2021
self.address != other.address) and self.changed(other))
2122

2223
def __repr__(self):
23-
return "{0}: [{1} ({2}) - {3}]".format(self.__class__.__name__,
24+
return "{0}: [{1} ({2}) - {3}]".format(self.__class__.__name__,
2425
self.address,
2526
" ".join(self._hostnames),
2627
self.status)
28+
2729
def __hash__(self):
2830
return (hash(self.status) ^ hash(self.address) ^
29-
hash(frozenset(self._services)) ^ hash(frozenset(" ".join(self._hostnames))))
31+
hash(frozenset(self._services)) ^
32+
hash(frozenset(" ".join(self._hostnames))))
3033

3134
def changed(self, other):
3235
return len(self.diff(other).changed())
@@ -67,7 +70,6 @@ def starttime(self):
6770
def endtime(self):
6871
return self._endtime
6972

70-
7173
def add_hostname(self, hostname):
7274
self._hostnames.append(hostname)
7375

@@ -85,15 +87,16 @@ def get_ports(self):
8587
return [(p.port, p.protocol) for p in self._services]
8688

8789
def get_open_ports(self):
88-
return [(p.port, p.protocol) for p in self._services if p.state == 'open']
90+
return ([(p.port, p.protocol)
91+
for p in self._services if p.state == 'open'])
8992

9093
def get_service(self, portno, protocol='tcp'):
9194
plist = [p for p in self._services if
9295
p.port == portno and p.protocol == protocol]
9396
return plist.pop() if len(plist) else None
9497

9598
def get_service_byid(self, id):
96-
service = [ s for s in self.service if s.id() == id ]
99+
service = [s for s in self.service if s.id() == id]
97100
if len(service) > 1:
98101
raise Exception("Duplicate services found in NmapHost object")
99102

@@ -104,19 +107,21 @@ def id(self):
104107
return self.address
105108

106109
def get_dict(self):
107-
d = dict([("%s.%s" % (s.__class__.__name__, str(s.id)), hash(s)) for s in self.services ])
108-
d.update({ 'address': self.address, 'status': self.status,
109-
'hostnames': " ".join(self._hostnames)})
110+
d = dict([("%s.%s" % (s.__class__.__name__,
111+
str(s.id)), hash(s)) for s in self.services])
112+
d.update({'address': self.address, 'status': self.status,
113+
'hostnames': " ".join(self._hostnames)})
110114
return d
111115

112116
def diff(self, other):
113117
return NmapDiff(self, other)
114118

119+
115120
class NmapService(object):
116121
def __init__(self, portid, protocol='tcp', state=None, service=None):
117122
try:
118123
self._portid = int(portid or -1)
119-
except ValueError, TypeError:
124+
except (ValueError, TypeError):
120125
raise
121126
if self._portid < 0 or self._portid > 65535:
122127
raise ValueError
@@ -126,18 +131,21 @@ def __init__(self, portid, protocol='tcp', state=None, service=None):
126131
self._service = service if service is not None else {}
127132

128133
def __eq__(self, other):
129-
return (self.id == other.id and self.changed(other) == 0)
134+
return (self.id == other.id and self.changed(other) == 0)
130135

131136
def __ne__(self, other):
132-
return (self.id != other.id or self.changed(other))
137+
return (self.id != other.id or self.changed(other))
133138

134139
def __repr__(self):
135-
return "{0}: [{1} - {2}/{3} {4} ({5})]".format(self.__class__.__name__, self.state,
136-
str(self.port), self.protocol,
137-
self.service, self.banner)
140+
return "{0}: [{1} {2}/{3} {4} ({5})]".format(self.__class__.__name__,
141+
self.state,
142+
str(self.port),
143+
self.protocol,
144+
self.service,
145+
self.banner)
138146

139147
def __hash__(self):
140-
return (hash(self.port) ^ hash(self.protocol) ^ hash(self.state) ^
148+
return (hash(self.port) ^ hash(self.protocol) ^ hash(self.state) ^
141149
hash(self.service) ^ hash(self.banner))
142150

143151
def changed(self, other):
@@ -159,7 +167,7 @@ def protocol(self):
159167
def state(self):
160168
return self._state['state'] if 'state' in self._state else None
161169

162-
def add_state(self, state={}):
170+
def add_state(self, state={}):
163171
self._state = state
164172

165173
@property
@@ -170,19 +178,24 @@ def add_service(self, service={}):
170178
self._service = service
171179

172180
def open(self):
173-
return True if self._state['state'] and self._state['state'] == 'open' else False
181+
return (True
182+
if self._state['state'] and self._state['state'] == 'open'
183+
else False)
174184

175185
@property
176186
def banner(self):
177-
notrelevant = ['name', 'method', 'conf' ]
187+
notrelevant = ['name', 'method', 'conf']
178188
b = ''
179189
if self._service and self._service['method'] == "probed":
180-
b = " ".join([ k + ": " + self._service[k] for k in self._service.keys() if k not in notrelevant ])
190+
b = " ".join([k + ": " + self._service[k]
191+
for k in self._service.keys()
192+
if k not in notrelevant])
181193
return b
182194

183195
def get_dict(self):
184-
return { 'id': self.id, 'port': str(self.port), 'protocol': self.protocol,
185-
'banner': self.banner, 'service': self.service, 'state': self.state }
196+
return ({'id': self.id, 'port': str(self.port),
197+
'protocol': self.protocol, 'banner': self.banner,
198+
'service': self.service, 'state': self.state})
186199

187-
def diff(self, other):
200+
def diff(self, other):
188201
return NmapDiff(self, other)

libnmap/diff.py

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python
22

3+
34
class DictDiffer(object):
45
"""
56
Calculate the difference between two dictionaries as:
@@ -9,30 +10,44 @@ class DictDiffer(object):
910
(4) keys same in both and unchanged values
1011
"""
1112
def __init__(self, current_dict, past_dict):
12-
self.current_dict, self.past_dict = current_dict, past_dict
13-
self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
13+
self.current_dict = current_dict
14+
self.past_dict = past_dict
15+
self.set_current = set(current_dict.keys())
16+
self.set_past = set(past_dict.keys())
1417
self.intersect = self.set_current.intersection(self.set_past)
18+
1519
def added(self):
16-
return self.set_current - self.intersect
20+
return self.set_current - self.intersect
21+
1722
def removed(self):
18-
return self.set_past - self.intersect
23+
return self.set_past - self.intersect
24+
1925
def changed(self):
20-
return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
26+
return (set(o for o in self.intersect
27+
if self.past_dict[o] != self.current_dict[o]))
28+
2129
def unchanged(self):
22-
return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])
30+
return (set(o for o in self.intersect
31+
if self.past_dict[o] == self.current_dict[o]))
32+
2333

2434
class NmapDiff(DictDiffer):
2535
def __init__(self, nmap_obj1, nmap_obj2):
2636
if nmap_obj1.id != nmap_obj2.id:
27-
raise NmapDiffException("Comparing objects with non-matching id keys")
28-
37+
raise NmapDiffException("Comparing objects with non-matching id")
38+
2939
self.object1 = nmap_obj1.get_dict()
3040
self.object2 = nmap_obj2.get_dict()
3141

3242
DictDiffer.__init__(self, self.object1, self.object2)
43+
3344
def __repr__(self):
34-
return ("added: [{0}] -- changed: [{1}] -- unchanged: [{2}] -- removed [{3}]".format(
35-
self.added(), self.changed(), self.unchanged(), self.removed()))
45+
return ('added: [{0}] -- changed: [{1}] -- \
46+
unchanged: [{2}] -- removed [{3}]'.format(self.added(),
47+
self.changed(),
48+
self.unchanged(),
49+
self.removed()))
50+
3651

3752
class NmapDiffException(Exception):
3853
def __init__(self, msg):

libnmap/parser.py

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,15 @@
44
from StringIO import StringIO
55
from libnmap import NmapHost, NmapService
66

7+
78
class NmapParser(object):
89
@classmethod
910
def parse(cls, nmap_data=None, type='XML'):
10-
nmap_scan = { '_nmaprun': {}, '_scaninfo': {}, '_hosts': [], '_runstats': {} }
11+
nmap_scan = {'_nmaprun': {}, '_scaninfo': {},
12+
'_hosts': [], '_runstats': {}}
1113
if not nmap_data:
12-
raise NmapParserException("No report data to parse: please provide a file")
14+
raise NmapParserException("No report data to parse: \
15+
please provide a file")
1316

1417
try:
1518
if isinstance(nmap_data, str):
@@ -23,15 +26,18 @@ def parse(cls, nmap_data=None, type='XML'):
2326
if root.tag == 'nmaprun':
2427
nmap_scan['_nmaprun'] = cls.__format_attributes(root)
2528
else:
26-
raise NmapParserException('Unpexpected data structure for XML root node')
29+
raise NmapParserException("Unpexpected data structure \
30+
for XML root node")
2731
for el in root:
2832
if el.tag == 'scaninfo':
2933
nmap_scan['_scaninfo'] = cls.parse_scaninfo(el)
3034
elif el.tag == 'host':
3135
nmap_scan['_hosts'].append(cls.parse_host(el))
3236
elif el.tag == 'runstats':
3337
nmap_scan['_runstats'] = cls.parse_runstats(el)
34-
#else: print "struct pparse unknown attr: %s value: %s" % (el.tag, el.get(el.tag))
38+
#else:
39+
# print "struct pparse unknown attr: %s value: %s" %
40+
# (el.tag, el.get(el.tag))
3541
return nmap_scan
3642

3743
@classmethod
@@ -45,7 +51,8 @@ def parse_fromfile(cls, nmap_report_path, type="XML"):
4551
r = cls.parse(fd, type)
4652
fd.close()
4753
else:
48-
raise NmapParserException("Nmap data file could not be found or permissions were not set correctly")
54+
raise NmapParserException("Nmap data file could not be found \
55+
or permissions were not set correctly")
4956
return r
5057

5158
@classmethod
@@ -60,7 +67,7 @@ def parse_fromdict(cls, rdict):
6067
hlist = []
6168
for h in r['_hosts']:
6269
slist = []
63-
for s in h['__NmapHost__']['_services']:
70+
for s in h['__NmapHost__']['_services']:
6471
cname = '__NmapService__'
6572
slist.append(NmapService(portid=s[cname]['_portid'],
6673
protocol=s[cname]['_protocol'],
@@ -76,7 +83,7 @@ def parse_fromdict(cls, rdict):
7683
hlist.append(nh)
7784
nreport['_hosts'] = hlist
7885
return nreport
79-
86+
8087
@classmethod
8188
def parse_scaninfo(cls, scaninfo_data):
8289
xelement = cls.__format_element(scaninfo_data)
@@ -96,7 +103,9 @@ def parse_host(cls, scanhost_data):
96103
nhost.add_service(port)
97104
elif xh.tag in ('status', 'address'):
98105
setattr(nhost, xh.tag, cls.__format_attributes(xh))
99-
#else: print "struct host unknown attr: %s value: %s" % (h.tag, h.get(h.tag))
106+
#else:
107+
# print "struct host unknown attr: %s value: %s" %
108+
# (h.tag, h.get(h.tag))
100109
return nhost
101110

102111
@classmethod
@@ -117,7 +126,9 @@ def parse_ports(cls, scanports_data):
117126
if xservice.tag == 'port':
118127
nport = cls.parse_port(xservice)
119128
ports.append(nport)
120-
#else: print "struct port unknown attr: %s value: %s" % (h.tag, h.get(h.tag))
129+
#else:
130+
# print "struct port unknown attr: %s value: %s" %
131+
# (h.tag, h.get(h.tag))
121132
return ports
122133

123134
@classmethod
@@ -129,15 +140,17 @@ def parse_port(cls, scanport_data):
129140

130141
nport.add_state(cls.__format_attributes(xelement.find('state')))
131142
if not nport.state:
132-
raise NmapParserException("Service state is not known or could not be parsed")
143+
raise NmapParserException("Service state is not known \
144+
or could not be parsed")
133145

134146
nport.add_service(cls.__format_attributes(xelement.find('service')))
135147
if not nport.service:
136-
raise NmapParserException("Service name is not known or could not be parsed")
148+
raise NmapParserException("Service name is not known \
149+
or could not be parsed")
137150

138151
return nport
139152

140-
@classmethod
153+
@classmethod
141154
def parse_runstats(cls, scanrunstats_data):
142155
xelement = cls.__format_element(scanrunstats_data)
143156

@@ -152,7 +165,8 @@ def parse_runstats(cls, scanrunstats_data):
152165
rdict[s.tag]['down'] = s.get('down')
153166
rdict[s.tag]['total'] = s.get('total')
154167
else:
155-
raise NmapParserException('Unpexpected data structure for <runstats>')
168+
raise NmapParserException('Unpexpected data structure \
169+
for <runstats>')
156170

157171
return rdict
158172

@@ -162,27 +176,33 @@ def __format_element(elt_data):
162176
try:
163177
xelement = ET.fromstring(elt_data)
164178
except:
165-
raise NmapParserException("Error while trying to instanciate XML Element from string {0}".format(elt_data))
179+
raise NmapParserException("Error while trying \
180+
to instanciate XML Element from \
181+
string {0}".format(elt_data))
166182
elif ET.iselement(elt_data):
167183
xelement = elt_data
168184
else:
169-
raise NmapParserException("Error while trying to parse supplied data: unsupported format")
185+
raise NmapParserException("Error while trying to parse supplied \
186+
data: unsupported format")
170187
return xelement
171188

172189
@staticmethod
173190
def __format_attributes(elt_data):
174191
r = {}
175192
if not ET.iselement(elt_data):
176-
raise NmapParserException("Error while trying to parse supplied data attributes: format is not XML")
193+
raise NmapParserException("Error while trying to parse supplied \
194+
data attributes: format is not XML")
177195
try:
178196
for k in elt_data.keys():
179197
r[k] = elt_data.get(k)
180198
if r[k] is None:
181-
raise NmapParserException("Error while trying to build-up element attributes")
199+
raise NmapParserException("Error while trying to build-up \
200+
element attributes")
182201
except:
183202
raise
184203
return r
185204

205+
186206
class NmapParserException(Exception):
187207
def __init__(self, msg):
188208
self.msg = msg

0 commit comments

Comments
 (0)