Skip to content

Commit cb5e43e

Browse files
authored
Merge pull request #388 from leiweibau/next_update
Next update
2 parents 2dd449d + afa775a commit cb5e43e

File tree

12 files changed

+329
-27
lines changed

12 files changed

+329
-27
lines changed

back/pialert.py

Lines changed: 53 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,11 @@ def set_db_file_permissions():
132132
# Set permissions
133133
os.system("sudo /usr/bin/chown " + get_username() + ":www-data " + PIALERT_DB_FILE)
134134
os.system("sudo /usr/bin/chmod 775 " + PIALERT_DB_FILE)
135+
136+
# Set permissions Experimental
137+
# os.system("sudo /usr/bin/chown " + get_username() + ":www-data " + PIALERT_DB_FILE + "*")
138+
# os.system("sudo /usr/bin/chmod 775 " + PIALERT_DB_FILE + "*")
139+
135140
# Get permissions
136141
fileinfo = Path(PIALERT_DB_FILE)
137142
file_stat = fileinfo.stat()
@@ -376,7 +381,7 @@ def NewVersion_FrontendNotification(newVersion,update_notes):
376381
if not os.path.exists(file_path):
377382
print(" Create Frontend Notification.")
378383
else:
379-
print(" Update Frontend Notification.")
384+
print(" Update Frontend Notification.")
380385
with open(file_path, 'w') as file:
381386
file.write(update_notes)
382387
else:
@@ -694,7 +699,7 @@ def query_MAC_vendor(pMAC):
694699
# not Found
695700
except subprocess.CalledProcessError :
696701
return -1
697-
702+
698703
#===============================================================================
699704
# SCAN NETWORK
700705
#===============================================================================
@@ -719,7 +724,7 @@ def scan_network():
719724
print(' Exiting...\n')
720725
return 1
721726

722-
# ScanCycle data
727+
# ScanCycle data
723728
cycle_interval = scanCycle_data['cic_EveryXmin']
724729
#arpscan_retries = scanCycle_data['cic_arpscanCycles']
725730
# arp-scan command
@@ -860,8 +865,8 @@ def execute_arpscan():
860865

861866
# multiple interfaces
862867
if type(SCAN_SUBNETS) is list:
863-
print(" arp-scan: Multiple interfaces")
864-
for interface in SCAN_SUBNETS :
868+
print(" arp-scan: Multiple interfaces")
869+
for interface in SCAN_SUBNETS :
865870
arpscan_output += execute_arpscan_on_interface (interface)
866871
# one interface only
867872
else:
@@ -879,11 +884,11 @@ def execute_arpscan():
879884
for device in re.finditer (re_pattern, arpscan_output)]
880885

881886
# Delete duplicate MAC
882-
unique_mac = []
883-
unique_devices = []
887+
unique_mac = []
888+
unique_devices = []
884889

885890
for device in devices_list :
886-
if device['mac'] not in unique_mac:
891+
if device['mac'] not in unique_mac:
887892
unique_mac.append(device['mac'])
888893
unique_devices.append(device)
889894

@@ -939,27 +944,36 @@ def copy_pihole_network():
939944
sql.execute ("DETACH PH")
940945

941946
elif PIHOLE_VERSION == 6:
942-
#Debug
943-
#PIHOLE6_URL = 'https://localhost:443'
944-
#PIHOLE6_PASSWORD = '######'
947+
global PIHOLE6_URL
948+
global PIHOLE6_PASSWORD
945949

946-
if not PIHOLE6_PASSWORD or not PIHOLE6_URL:
950+
if not PIHOLE6_PASSWORD or not PIHOLE6_URL :
947951
print(' ...Skipped (Config Error)')
948952
return
949953

950954
if not PIHOLE6_URL.endswith('/'):
951955
PIHOLE6_URL += '/'
952956

957+
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
953958
headers = {
954959
"accept": "application/json",
955960
"content-type": "application/json"
956961
}
957962
data = {
958963
"password": PIHOLE6_PASSWORD
959964
}
960-
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
961-
response = requests.post(PIHOLE6_URL+'api/auth', headers=headers, json=data, verify=False)
962-
# print(response.json())
965+
try:
966+
response = requests.post(PIHOLE6_URL+'api/auth', headers=headers, json=data, verify=False, timeout=15)
967+
except requests.exceptions.Timeout:
968+
print(f" Request timed out after 15 seconds")
969+
return
970+
except requests.exceptions.ConnectionError as e:
971+
print(f" Connection error occurred")
972+
return
973+
except Exception as e:
974+
print(f" An unexpected error occurred")
975+
return
976+
963977
response_json = response.json()
964978

965979
if response.status_code == 200 and response_json['session']['valid'] == True :
@@ -972,20 +986,28 @@ def copy_pihole_network():
972986
result = {}
973987
deviceslist = raw_deviceslist.json()
974988

989+
# If pi-hole is outside the local Pi.Alert network and cannot be found with arp.
990+
pihole_host_ip = get_ip_from_hostname(PIHOLE6_URL)
991+
975992
for device in deviceslist['devices']:
976993
hwaddr = device['hwaddr']
977994
lastQuery = device['lastQuery']
978995
macVendor = device['macVendor']
979996

997+
# skip lo interface
980998
if hwaddr == "00:00:00:00:00:00":
981999
continue
9821000

9831001
for ip_info in device['ips']:
9841002
ip = ip_info['ip']
9851003
name = ip_info['name'] if ip_info['name'] not in [None, ""] else "(unknown)"
986-
1004+
9871005
# Check whether the IP could be a IPv4 address
9881006
if '.' in ip:
1007+
# Change the “lastQuery” variable to mark the Pi-hole host as “active”
1008+
if pihole_host_ip == ip:
1009+
lastQuery = str(int(datetime.datetime.now().timestamp()))
1010+
9891011
result[hwaddr] = {
9901012
"ip": ip,
9911013
"name": name,
@@ -995,18 +1017,32 @@ def copy_pihole_network():
9951017

9961018
# print(result)
9971019
for hwaddr, details in result.items():
998-
cursor.execute("""
1020+
sql.execute("""
9991021
INSERT INTO PiHole_Network (PH_MAC, PH_Vendor, PH_LastQuery, PH_Name, PH_IP)
10001022
VALUES (?, ?, ?, ?, ?)
10011023
""", (hwaddr, details['macVendor'], details['lastQuery'], details['name'], details['ip']))
10021024

1025+
result = {}
1026+
deviceslist = raw_deviceslist.json()
1027+
10031028
else:
10041029
print("Auth required")
10051030
return
10061031

10071032
else:
10081033
print(' ...Unsupported Version')
10091034

1035+
#-------------------------------------------------------------------------------
1036+
def get_ip_from_hostname(url):
1037+
try:
1038+
hostname_port = url.replace("http://", "").replace("https://", "").split('/')[0]
1039+
hostname = hostname_port.split(':')[0]
1040+
ip_address = socket.gethostbyname(hostname)
1041+
return ip_address
1042+
except socket.gaierror as e:
1043+
ip_address = ""
1044+
return ip_address
1045+
10101046
#-------------------------------------------------------------------------------
10111047
def read_fritzbox_active_hosts():
10121048
# create table if not exists

config/version.conf

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
VERSION = ''
22
VERSION_YEAR = '2024'
3-
VERSION_DATE = '2024-09-01'
3+
VERSION_DATE = '2024-09-17'

0 commit comments

Comments
 (0)