-
Notifications
You must be signed in to change notification settings - Fork 1
/
kentang.py
411 lines (376 loc) · 9.56 KB
/
kentang.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/usr/bin/env python
'''
Kentang: Simple Network Monitoring Program
- Features:
- protocols: http, https, ftp, smtp, imap4, imap4ssl, pop3, pop3ssl
- multi threaded
- multi platform
- command line interface
- simple event handler (ok/fail)
- simple configuration file (INI file)
- Configuration section
[<host>[,optional tag]]
protocol = <supported protocol>
port = [optional, port]
ok = [optional, execute this command if ok]
fail = [optional, execute this command if fails]
- Arguments passed to event handler:
- time
- hostname
- port
- Started by: Noprianto <nop@noprianto.com>
- Website: http://www.noprianto.com
- License: GPL
'''
import os
import sys; sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
import ConfigParser
import time
import threading
import httplib
import ftplib
import smtplib
import imaplib
import poplib
import socket
NAME = 'kentang'
VERSION = ( (0, 30), '26-OCT-2012-UTC+7' )
PROTOCOLS = (
'http',
'https',
'ftp',
'smtp',
'imap4',
'imap4ssl',
'pop3',
'pop3ssl',
)
PROTOLEN = max([len(x) for x in PROTOCOLS])
ITEMS = [
'protocol',
'port',
'ok',
'fail'
]
TIMEOUT = 10
ERRORS = {
0 : ['', '', ''],
1 : ['', 'Config file not specified', ''],
2 : ['', 'Unable to open config file', ''],
3 : ['', 'Error parsing config file', ''],
64 : ['', 'Interrupted by user', ''],
127: ['', 'General error', ''],
}
def error(code, func='', extra=''):
global ERRORS
#
ERRORS[code][0] = func
ERRORS[code][2] = extra
#
return code
def log(msg, newline=1, stream=sys.stdout):
try:
newline = int(newline)
except ValueError:
newline = 0
#
end = os.linesep * newline
#
if not stream in [sys.stdout, sys.stderr]:
return
#
stream.write('%s%s' %(msg, end) )
def print_version():
v = '.'.join([str(x) for x in VERSION[0]])
s = '%s version %s (%s)' %(NAME, v, VERSION[1])
log(s)
#
return error(0)
def parse_config(file):
log('Using config file: %s' %(file))
ret = []
#
c = ConfigParser.ConfigParser()
#
try:
c.read(file)
except:
return ret
#
s = c.sections()
for i in s:
error = 0
entry = {}
try:
host = i.split(',')[0].strip()
except:
host = ''
entry['host'] = host
#
for j in ITEMS:
try:
e = c.get(i, j).strip()
except ConfigParser.NoOptionError:
e = ''
#
if j == 'protocol' and e not in PROTOCOLS:
log('Unsupported protocol: %s(%s), ignoring...' %(
e, i), stream=sys.stderr)
error = 1
elif j == 'port':
try:
e = int(e)
except ValueError:
e = None
#
entry[j] = e
#
if not error:
ret.append(entry)
#
return ret
def working(config):
socket.setdefaulttimeout(TIMEOUT)
log('Timeout: %ds' %(TIMEOUT))
log('Found %d host(s)' %(len(config)))
log('Please wait...')
start = time.time()
#
threads = []
for i in config:
thread = HostChecker(i)
threads.append(thread)
thread.start()
#
while True:
for i in threads:
if not i.isAlive():
threads.remove(i)
if not threads:
break
#
finish = time.time()
#
msg = 'Done, checked %d host(s) in %0.2f second(s)' %(
len(config), finish-start
)
log(msg)
#
return error(0)
def main(argv):
print_version()
try:
c = argv[1]
except IndexError:
return error(1)
#
c = os.path.abspath(c)
try:
ct = open(c)
except IOError:
return error(2, extra=c)
#
config = parse_config(c)
if not config:
return error(3, extra=c)
#
try:
ret = working(config)
except KeyboardInterrupt:
return error(64)
#
return ret
class HostChecker(threading.Thread):
def __init__(self, host):
threading.Thread.__init__(self)
self.host = host
def handler_http(self, secure=False):
ret = 0
status = '000'
info = '[FAILED]'
port = self.host['port']
try:
if secure:
if not port:
port = 443
self.host['port'] = port
conn = httplib.HTTPSConnection(self.host['host'], port)
else:
if not port:
port = 80
self.host['port'] = port
conn = httplib.HTTPConnection(self.host['host'], port)
#
conn.request('HEAD', '/')
res = conn.getresponse()
status = str(res.status)
msg = '%s: %s:%s %s ' %(
self.host['protocol'].ljust(PROTOLEN),
self.host['host'],
port,
status
)
except:
msg = '%s: %s:%s ' %(
self.host['protocol'].ljust(PROTOLEN),
self.host['host'],
port,
)
#
if status[0] in ['1', '2', '3']:
info = '[OK]'
ret = 1
#
log(msg + info)
#
return ret
def handler_https(self):
return self.handler_http(secure=True)
def handler_ftp(self):
ret = 0
info = '[FAILED]'
#
port = self.host['port']
if not port:
port = 21
self.host['port'] = port
#
try:
conn = ftplib.FTP()
conn.connect(self.host['host'], port)
info = '[OK]'
ret = 1
except:
ret = 0
#
msg = '%s: %s:%s ' %(
self.host['protocol'].ljust(PROTOLEN),
self.host['host'],
port,
)
log(msg + info)
#
return ret
def handler_smtp(self):
ret = 0
info = '[FAILED]'
#
port = self.host['port']
if not port:
port = 25
self.host['port'] = port
#
try:
conn = smtplib.SMTP(self.host['host'], port)
info = '[OK]'
ret = 1
except:
ret = 0
#
msg = '%s: %s:%s ' %(
self.host['protocol'].ljust(PROTOLEN),
self.host['host'],
port,
)
log(msg + info)
#
return ret
def handler_imap4(self, secure=False):
ret = 0
info = '[FAILED]'
#
port = self.host['port']
try:
if secure:
if not port:
port = 993
self.host['port'] = port
conn = imaplib.IMAP4_SSL(self.host['host'], port)
else:
if not port:
port = 143
self.host['port'] = port
conn = imaplib.IMAP4(self.host['host'], port)
#
info = '[OK]'
ret = 1
except:
ret = 0
#
msg = '%s: %s:%s ' %(
self.host['protocol'].ljust(PROTOLEN),
self.host['host'],
port,
)
log(msg + info)
#
return ret
def handler_imap4ssl(self):
return self.handler_imap4(secure=True)
def handler_pop3(self, secure=False):
ret = 0
info = '[FAILED]'
#
port = self.host['port']
try:
if secure:
if not port:
port = 995
self.host['port'] = port
conn = poplib.POP3_SSL(self.host['host'], port)
else:
if not port:
port = 110
self.host['port'] = port
conn = poplib.POP3(self.host['host'], port)
#
info = '[OK]'
ret = 1
except:
ret = 0
#
msg = '%s: %s:%s ' %(
self.host['protocol'].ljust(PROTOLEN),
self.host['host'],
port,
)
log(msg + info)
#
return ret
def handler_pop3ssl(self):
return self.handler_pop3(secure=True)
def run(self):
fn = 'handler_' + self.host['protocol']
func = getattr(HostChecker, fn)
ret = func(self)
#
cmd = ''
if not ret:
if self.host['fail']:
htype = 'fail'
cmd = self.host['fail']
else:
if self.host['ok']:
htype = 'ok'
cmd = self.host['ok']
#
if cmd:
cmds = "%s '%s' '%s' '%s'" %(
cmd, time.asctime(),
self.host['host'],
self.host['port'])
log(' Execute %s %s-%s handler: %s' %(
self.host['host'],
self.host['protocol'],
htype,
cmd
))
os.system(cmds)
if __name__ == '__main__':
ret = main(sys.argv)
if ret > 0:
err = [x for x in ERRORS[ret] if x.strip()]
msg = ': '.join(err)
log(msg, stream=sys.stderr)
#
sys.exit(ret)