Skip to content
Snippets Groups Projects

Backend

Merged Martin Petráček requested to merge backend into master
Viewing commit da72be7b
Show latest version
2 files
+ 49
1
Preferences
Compare changes
Files
2
+ 27
1
#!/usr/bin/python
#
# DevDetect - small utility to detect new devices on local network
# Copyright (C) 2017 CZ.NIC, z.s.p.o. (http://www.nic.cz/)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# -*- coding: utf-8 -*-
import time
@@ -8,6 +25,7 @@ import os
from threading import Timer
class macAddrStore():
#keeps MAC addresses as dictionary, MAC address is the key, timestamp is the value
def __init__(self):
self.__load()
self.save_interval=30*60 #TBD: move to configuration
@@ -17,9 +35,12 @@ class macAddrStore():
t.start()
def __del__(self):
#save values on program exit
self.__save()
def update(self, mac):
#update MAC address (its timetamp)
#if it wasn't seen before, register it (also save file immdiatelly) and create notification for user
if mac in self.known:
self.known[mac]=int(time.time())
else:
@@ -29,6 +50,8 @@ class macAddrStore():
os.system("/usr/bin/create_notification -s news 'Ve vasi siti se objevilo nove zarizeni (MAC adresa %s)' 'New device (MAC address %s) appeared on your network.'" % (mac, mac)) #TBD: Czech non-ascii characters...
def __save(self):
#save known MAC addresses to file
#to prevent file corruption, MAC addresses are at first written to temporary files which is then moved to correct location
f = open('/tmp/known_macs.txt', 'w')
print >>f, json.dumps(self.known)
print json.dumps(self.known)
@@ -36,6 +59,7 @@ class macAddrStore():
shutil.move('/tmp/known_macs.txt', '/usr/share/known_macs.txt')
def __load(self):
#load addresses (if they exist)
try:
f = open('/usr/share/known_macs.txt', 'r')
self.known=json.load(f)
@@ -44,6 +68,8 @@ class macAddrStore():
self.known={}
def __timeout(self):
#save MAC addresses to file
#also clean MAC addresses that were inactive for too long
for mac in self.known.keys():
if self.known[mac] < int(time.time()) - self.mac_timeout:
del self.known_macs[mac]