-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathformat_ports.py
More file actions
executable file
·48 lines (40 loc) · 1.26 KB
/
format_ports.py
File metadata and controls
executable file
·48 lines (40 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python2.7
import argparse
import sys
import re
from cStringIO import StringIO
def group_consec(nums):
# Assumes a non-empty list
nums.sort()
sio = StringIO()
prev = nums[0]
for i, n in enumerate(nums):
if i > 0 and n - nums[i-1] > 1:
sio.write("%d" % prev)
if nums[i-1] != prev:
sio.write("-%d" % nums[i-1])
sio.write(",")
prev = n
if prev != n:
sio.write("%d-" % prev)
sio.write("%d" % n)
return sio.getvalue()
########
# MAIN #
########
if __name__ == '__main__':
desc = 'Group consecutive ports to a nmap suitabel format.'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('file',
nargs='?',
type=argparse.FileType('r'),
action='store',
help='file containing a list of ports split by a newline, otherwise read from STDIN',
metavar='FILE',
default=sys.stdin)
args = parser.parse_args()
try:
ports = [int(line.strip()) for line in args.file if len(line.strip())>0 and line[0] is not '#']
except KeyboardInterrupt:
exit()
print group_consec(ports)