-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIPsort.py
executable file
·61 lines (51 loc) · 1.86 KB
/
IPsort.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
##
# Fri Aug 1 10:01:22 CEST 2008 -- A.G. van der Vlies
#-
# Created for a coworker who needed a IPsort utility...
#
#- HvD -- di 19 mei 2020 15:05:19 CEST
# Found argparse :-)
import re
import sys
import socket
separator = ','
def do_magic(trick, sep):
"""
Grok list (e.g. generated by hostsdeny), Strip none IP things. Spilt on
separator char and sort (lambda funtion)
"""
IPsort = lambda a1, a2: cmp(socket.inet_aton(a1), socket.inet_aton(a2))
Summary = {}
input = open(trick, "r")
for RawLine in input.readlines():
if RawLine[0] == '#': continue #Skip comment
if RawLine[0] == '\n': continue #Skip empty lines
RawLine = re.sub(" +", "", RawLine) #Reduce spaces
RawLine = re.sub("\n", "", RawLine) #Reduce surplus of newline and carriage return
RawLine = re.sub("\r\n", "", RawLine)
CookedLine, IPno = RawLine.split(sep, 1)
##
# Vr 9 dec 2016 16:31:53 CET -- HvD
# Grmph. IP-strings cannot end in a '.' See man 3 inet...
#
IPno = re.sub("\.$", "", IPno)
Summary[IPno] = CookedLine
#print "Summary: ", Summary
#print 'Keys: ', Summary.keys()
#print 'Values: ', Summary.values()
Addresses = Summary.keys()
Addresses.sort(IPsort)
input.close()
return Addresses
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Split a <file> containing IPno's using <separator> and sort it.")
parser.add_argument('-s', '--separator', type=str, help='Seperator', default=';')
parser.add_argument('file', help='File do do magic on')
args = parser.parse_args()
file = args.file
separator = args.separator
result = do_magic(file, separator)
for item in result:
print "%s" % (item)