-
Notifications
You must be signed in to change notification settings - Fork 3
/
nginx_checker.py
106 lines (92 loc) · 3.63 KB
/
nginx_checker.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
import telebot
import difflib
import json
from inotify_simple import INotify, flags
from threading import Thread
CONFIG_FILE = 'config.json'
def get_config():
try:
with open(CONFIG_FILE, 'rb') as openFile:
return json.load(openFile)
except:
print('File config tidak ditemukan')
return None
logs = get_config()['check_files']
checks = ["check" + str(i) + ".txt" for i in range(len(logs))]
for check in checks:
with open(check, 'w'):
pass
chatIds = get_config()['receiver_id']
botId = get_config()['bot_id']
bot = telebot.TeleBot(botId)
watch_flags = flags.MOVE_SELF | flags.MODIFY
def beda(log, check, inotify):
inotify.add_watch(log, watch_flags)
try:
for event in inotify.read(timeout=1):
if event is not None:
for flag in flags.from_mask(event.mask):
if str(flag) == 'flags.MODIFY':
with open(log, "r") as logFile, open(check) as checkFile:
loglines = logFile.readlines()
checklines = checkFile.readlines()
d = difflib.Differ()
diff = d.compare(loglines, checklines)
perbedaan = "".join(x[2:] for x in diff if x.startswith('- '))
if perbedaan != "":
try:
kirim = log + ' ERROR TERDETEKSI:\n' + perbedaan
for chatId in chatIds:
bot.send_message(chatId, kirim)
with open(check, "a+") as appendFile:
appendFile.write(perbedaan)
except:
print("Gagal mengirim error")
else:
pass
elif str(flag) == 'flags.MOVE_SELF':
with open(check, 'w'):
pass
elif str(flag) == 'flags.IGNORED':
print("warning")
for chatId in chatIds:
bot.send_message(chatId, "Peringatan! file error.log diubah secara manual")
else:
print(str(flag))
for chatId in chatIds:
bot.send_message(chatId, str(flag))
except:
print("error event")
inotify.rm_watch(log)
def start_thread(log, check):
inotify = INotify()
i = 1
while 1:
if i == 1:
with open(log, "r") as logFile, open(check) as checkFile:
loglines = logFile.readlines()
checklines = checkFile.readlines()
d = difflib.Differ()
diff = d.compare(loglines, checklines)
perbedaan = "".join(x[2:] for x in diff if x.startswith('- '))
if perbedaan != "":
try:
kirim = log + ' ERROR TERDETEKSI:\n' + perbedaan
for chatId in chatIds:
bot.send_message(chatId, kirim)
with open(check, "a+") as appendFile:
appendFile.write(perbedaan)
except:
print("Gagal mengirim error")
else:
pass
i += 1
beda(log, check, inotify)
if __name__ == "__main__":
threads = []
for index, log in enumerate(logs):
threads.append(
Thread(target=start_thread, args=(log, checks[index])))
threads[-1].start()
for t in threads:
t.join()