-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublicIpWhitelister.py
51 lines (43 loc) · 1.71 KB
/
publicIpWhitelister.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
import requests
import subprocess
from datetime import datetime
whitelistsFilePath = "/etc/crowdsec/parsers/s02-enrich/publicIpWhitelist.yaml"
curPubIpFilePath = "./currentIP"
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
def get_external_ip():
response = requests.get('https://api.ipify.org')
if response.status_code == 200:
return response.text
extIP = get_external_ip()
def read_from_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
return content
except Exception as e:
print(timestamp + ": Error while reading the file (" + filename + "):", str(e))
return None
def write_to_file(filename, content):
try:
with open(filename, 'w') as file:
file.write(content)
print(timestamp + ": File " + filename + " has been written successfully.")
except Exception as e:
print(timestamp + ": Error while writing the file (" + filename + "):", str(e))
def reloadCrowdsec():
subprocess.run(["systemctl", "reload", "crowdsec.service"], capture_output=True, text=True)
print(timestamp + ": crowdsec.service reloaded successfully.")
whitelistsFileContent = \
"name: phipzzz/publicIpWhitelist" + "\n" + \
"description: \"Whitelist events from public IPv4 address\"" + "\n" + \
"whitelist:" + "\n" + \
" reason: \"My public IP\"" + "\n" + \
" ip:" + "\n" + \
" - \"" + extIP + "\"" + "\n"
if read_from_file(curPubIpFilePath) != extIP:
print(timestamp + ": Public IP has changed. Setting new IP to whitelist.")
write_to_file(curPubIpFilePath, extIP)
write_to_file(whitelistsFilePath, whitelistsFileContent)
reloadCrowdsec()
else:
print(timestamp + ": IP didn't change")