1665b1e10062df3578493b29b3953c2418100b34
Benjamin Renard Initial commit

Benjamin Renard authored 8 years ago

1) #!/usr/bin/python
2) 
3) import dns.resolver
4) import re
5) import logging
6) import sys
7) from optparse import OptionParser
8) 
9) parser = OptionParser()
10) 
11) 
12) parser.add_option('-H',
13)                   '--host',
14)                   action="store",
15)                   type="string",
16)                   dest="host",
17)                   help="The host IP address to check")
18) 
19) parser.add_option('-B',
20)                   action="store",
21)                   type="string",
22)                   dest="bl",
23)                   help="Blacklist server(s) (separated by commas)")
24) 
25) parser.add_option('-t', '--timeout',
26)                   action="store",
27)                   type="int",
28)                   dest="timeout",
29)                   help="Timeout in second for DNS request (Default : 10s)",
30)                   default='10')
31) 
32) parser.add_option('-c',
33)                   action="store",
34)                   type="int",
35)                   dest="critical_count",
36)                   help="Critical blacklisted count")
37) 
38) parser.add_option('-C',
39)                   action="store",
40)                   type="int",
41)                   dest="critical_perc",
42)                   help="Critical blacklisted count as percentage (Default : 30%)",
43)                   default=30)
44) 
45) parser.add_option('-w',
46)                   action="store",
47)                   type="int",
48)                   dest="warning_count",
49)                   help="Warning blacklisted count")
50) 
51) parser.add_option('-W',
52)                   action="store",
53)                   type="int",
54)                   dest="warning_perc",
55)                   help="Warning blacklisted count as percentage (Default : 1%)",
56)                   default=1)
57) 
58) parser.add_option('-u',
59)                   action="store",
60)                   type="int",
61)                   dest="unknown_count",
62)                   help="Checking errors count triggering UNKNOWN status")
63) 
64) parser.add_option('-U',
65)                   action="store",
66)                   type="int",
67)                   dest="unknown_perc",
68)                   help="Checking errors count as percentage triggering UNKNOWN status (Default : 50%)",
69)                   default=50)
70) 
71) parser.add_option('-T',
72)                   '--threaded',
73)                   action="store_true",
74)                   help="Use thread for parallel checking",
75)                   dest="thread")
76) 
77) parser.add_option('-v',
78)                   '--verbose',
79)                   action="store_true",
80)                   help="Enable verbose mode",
81)                   dest="verbose")
82) 
83) parser.add_option('-d',
84)                   '--debug',
85)                   action="store_true",
86)                   help="Enable debug mode",
87)                   dest="debug")
88) 
89) (options, args) = parser.parse_args()
90) 
91) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
92) logger = logging.getLogger('BlChecker')
93) 
94) if options.debug:
95)         logger.setLevel(logging.DEBUG)
96) elif options.verbose:
97)         logger.setLevel(logging.INFO)
98) else:
99)         logger.setLevel(logging.WARNING)
100) 
101) logger.debug('Start with parameters : %s' % options)
102) 
103) # Check parameters
104) if not options.host or not options.bl:
105) 	logger.error('You must provide host IP address and blacklist server(s)')
Benjamin Renard Add ability to resolv host...

Benjamin Renard authored 8 years ago

106) 	sys.exit(3)
Benjamin Renard Initial commit

Benjamin Renard authored 8 years ago

107) 
108) options.host=options.host.strip()
109) 
Benjamin Renard Add ability to resolv host...

Benjamin Renard authored 8 years ago

110) def parseIP(ip):
111) 	return re.match('([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})',ip)
112) 
113) parsed_ip=parseIP(options.host)
114) 
115) if not parsed_ip:
116) 	logger.debug('Host parameter is not a valid IP address, try to resolv it as DNS name')
117) 	try:
118) 		import socket
119) 		res=socket.gethostbyname_ex(options.host)
120) 		logger.debug('gethostbyname_ex() result : %s' % str(res))
121) 		ip=res[2][0]
122) 		parsed_ip=parseIP(ip)
123) 		if not parsed_ip:
124) 			raise Exception('Fail to parse resolved IP %s address on name %s' % (ip,options.host))
125) 		logger.info('Resolved IP address corresponding to %s : %s' % (options.host,ip))
126) 	except socket.gaierror:
127) 		logger.error('Invalid host parameter (-H)')
128) 		sys.exit(3)
129) 	except Exception, e:
130) 		logger.error('Error resolving name %s : %s' % (options.host,e))
131) 		sys.exit(3)
132) 
Benjamin Renard Initial commit

Benjamin Renard authored 8 years ago

133) # Check method
Benjamin Renard Add ability to resolv host...

Benjamin Renard authored 8 years ago

134) def check(parsed_ip,bl,logger=None,timeout=10):
135) 	resolver = dns.resolver.Resolver()
136) 	resolver.timeout = timeout
137) 	resolver.lifetime = timeout
138) 	lookup="%s.%s.%s.%s.%s" % (parsed_ip.group(4),parsed_ip.group(3),parsed_ip.group(2),parsed_ip.group(1),bl)
139) 	try:
140) 		r=resolver.query(lookup,'TXT')
141) 		logger.info('Listed on BL %s (%s)' % (bl,lookup))
142) 		return True
143) 	except dns.resolver.NXDOMAIN:
144) 		logger.debug('Not listed on BL %s' % bl)
145) 		return False
146) 	except dns.exception.Timeout:
147) 		logger.info('Timeout looking on BL %s (%s)' % (bl,lookup))
148) 	except Exception, e:
149) 		logger.warning('Error looking on BL %s (%s) : %s' % (bl,lookup,e))
Benjamin Renard Initial commit

Benjamin Renard authored 8 years ago

150) 
151) 
152) # Split BL from args
153) BLs=options.bl.split(',')
154) BLs_count=len(BLs)
155) 
156) logger.debug('BLs count : %s' % BLs_count)
157) 
158) #### Check ####
159) 
160) results={}
161) 
162) if options.thread:
163) 	# Import lib
164) 	from threading import Thread
165) 
166) 	# Define Threader class
167) 	class BlChecker(Thread):
168) 
Benjamin Renard Add ability to resolv host...

Benjamin Renard authored 8 years ago

169) 		def __init__(self,parsed_ip,bl,timeout=10,logger=None):
Benjamin Renard Initial commit

Benjamin Renard authored 8 years ago

170) 			Thread.__init__(self)
171) 			if logger:
172) 				self.logger=logger
173) 			else:
174) 				self.logger=logging.getLogger('BlChecker')
175) 
Benjamin Renard Add ability to resolv host...

Benjamin Renard authored 8 years ago

176) 			self.parsed_ip = parsed_ip
Benjamin Renard Initial commit

Benjamin Renard authored 8 years ago

177) 			self.bl = bl
178) 			self.timeout = timeout
179) 		
180) 		def run(self):
Benjamin Renard Add ability to resolv host...

Benjamin Renard authored 8 years ago

181) 			results[bl]=check(self.parsed_ip,self.bl,logger=self.logger,timeout=self.timeout)
Benjamin Renard Initial commit

Benjamin Renard authored 8 years ago

182) 
183) 
184) 	# Create and start a thread for check on all BL
185) 	threads=[]
186) 
187) 	for bl in BLs:
Benjamin Renard Add ability to resolv host...

Benjamin Renard authored 8 years ago

188) 		th=BlChecker(parsed_ip,bl.strip(),timeout=options.timeout,logger=logger)
Benjamin Renard Initial commit

Benjamin Renard authored 8 years ago

189) 		th.start()
190) 		threads.append(th)
191) 
192) 	# Wait all BL checks ended
193) 	for th in threads:
194) 		th.join()
195) else:
196) 	for bl in BLs:
197) 		bl=bl.strip()
Benjamin Renard Add ability to resolv host...

Benjamin Renard authored 8 years ago

198) 		results[bl]=check(parsed_ip,bl,timeout=options.timeout,logger=logger)