-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
164 lines (136 loc) · 6.46 KB
/
main.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
import subprocess
import os
from telegram import TelegramBot
from sys import platform
import time
from map_hosts import MapHosts
from shinobi import Shinobi
import json
from config_helper import Config
from datetime import datetime
class ScanRede:
def __init__(self) -> None:
if platform == 'linux':
self.default_cachefile_path = os.path.join(os.path.expanduser('~'), 'scan-rede', 'cachefile')
self.default_log_path = os.path.join(os.path.expanduser('~'), 'scan-rede', 'log.txt')
self.logger(self.default_cachefile_path)
self.logger(self.default_log_path)
else:
self.default_cachefile_path = 'cachefile'
self.default_log_path = 'log.txt'
config = Config()
self.telegram = TelegramBot()
self.shinobi = Shinobi()
self.config_parameters = config.get_config('parameters')
self.known_hosts = self.config_parameters['known_hosts']
self.watch_dog_hosts = self.config_parameters['watch_dog_hosts']
self.ping_command = self.config_parameters['ping_command']
self.reboot_cameras = self.config_parameters['reboot_cameras']
self.mapping = MapHosts(self.known_hosts)
self.ler_status()
self.scanear_rede()
self.monitorar_dispositivo()
self.change_status()
def change_status(self):
presence = self.valida_presence()
horario = self.valida_horario()
event_person = []
if presence or horario:
if self.current_status['status'] != True:
self.current_status['status'] = True
for k in self.map:
if self.map[k]["action"] == "Saiu":
event_person.append(k)
self.shinobi.ativar()
self.telegram.notificar(f"Notificações ativadas, {' '.join(map(str, event_person))} Saiu!")
else:
if self.current_status['status'] != False:
self.current_status['status'] = False
for k in self.map:
if self.map[k]["action"] == "Entrou":
event_person.append(k)
self.shinobi.desativar()
self.telegram.notificar(f"Notificações desativadas, {' '.join(map(str, event_person))} Entrou!")
self.gravar_status()
def valida_horario(self) -> bool:
self.logger(time.strftime("%H:%M:%S"))
if time.strftime("%H:%M:%S") >= self.config_parameters['time_range']['start'] and time.strftime("%H:%M:%S") <= self.config_parameters['time_range']['end']:
return True
else:
return False
def valida_presence(self) -> bool:
self.current_presence_list = []
if self.map != []:
for k in self.map:
if self.map[k]["action"] != "Saiu":
self.current_presence_list.append(k)
if self.current_presence_list != []:
self.current_status['presence'] = self.current_presence_list
return False
else:
self.current_status['presence'] = self.current_presence_list
return True
def gravar_status(self):
json_file = json.dumps(self.current_status, indent=4)
with open(self.default_cachefile_path, 'w') as file:
file.write(json_file)
def ler_status(self):
try:
with open(self.default_cachefile_path, 'r') as file:
self.current_status = json.load(file)
except Exception as e:
self.logger(e)
self.default_status()
with open(self.default_cachefile_path, 'r') as file:
self.current_status = json.load(file)
def default_status(self):
self.logger("cachefile não encontrado! gerando um a partir do modelo...")
status = {
"presence": [],
"status": True,
"host_inoperante": False
}
json_file = json.dumps(status, indent=4)
with open(self.default_cachefile_path, 'w') as file:
file.write(json_file)
def scanear_rede(self):
if platform == 'linux':
output = subprocess.getoutput(self.config_parameters["arp_scan_command"])
self.logger(output)
self.arp_hosts = output.split("\n")
self.logger(self.arp_hosts)
self.map = self.mapping.match(self.arp_hosts, self.current_status['presence'])
self.logger(self.map)
else:
self.arp_hosts = ["0c:cb:85:36:c6:39"]
self.map = self.mapping.match(self.arp_hosts, self.current_status['presence'])
self.logger(self.map)
def dispositivo_online(self, ip):
packet_received = subprocess.getoutput(self.ping_command.format(ip_address=ip))
if int(packet_received) == 0:
return False
else:
return True
def monitorar_dispositivo(self):
'''Monitora dispositivo na rede e toma uma ação caso o dispositivo não seja encontrado.'''
for host in self.watch_dog_hosts:
for k, v in host.items():
if not self.current_status['host_inoperante'] and not self.dispositivo_online(v):
self.telegram.notificar(f'Dispositivo {k} não foi encontrado na rede!')
self.telegram.notificar(f'Tentando reinicia-lo...')
subprocess.getoutput(self.reboot_cameras)
time.sleep(120)
if self.dispositivo_online(v):
self.telegram.notificar(f'Dispositivo {k} foi encontrado novamente!')
continue
self.telegram.notificar(f'Dispositivo {k} continua inoperante!')
self.current_status['host_inoperante'] = True # Evita notificar a cada intervalo
if self.dispositivo_online(v) and self.current_status['host_inoperante']:
self.telegram.notificar(f'Dispositivo {k} encontrado novamente!')
self.current_status['host_inoperante'] = False # Evita notificar a cada intervalo
def logger(self, message):
print(message)
with open(self.default_log_path, 'a') as log:
log.writelines(f"{datetime.now()}: {str(message)}\n")
if __name__ == '__main__':
ScanRede()