I have written a Python-based daemon which blocks malicious IPs based on certain parameters. Now, I want to auto unblock (delete rule) the IP after 1 hour but am not sure how to use timer/scheduler module with my code.
I know the alternative methods can be:
but I have limitations and can't use the above mentioned alternative methods.
My main code is running in a WHILE(1) loop, so its blocking IPs. How to make a parallel module/function inside my python code that will execute the IPTABLES -D
command to remove the IPs? Each IP will have its own specific time to be unblocked.
eg
Update:
while True:
if (ip_found == -1 and port_found == -1):
os.system("iptables -A INPUT -s "+str(s_addr)+" -j DROP")
print(str(s_addr) + " was a malcious IP and it is blocked")
else:
print("Not a malcious IP")
Logically, you may try the following steps:
You may schedule the dequeue process to run when the first item from the queue is to be removed or unblocked.
If you want the queue and dequeue logic in the same module, you may try something like:
while(1):
queue(List of IPs)
dequeue()
sleep(1000) # sleep for 1 second
Based on the code provided by you and my understanding, I can suggest to implement something like the following:
import os
from datetime import datetime, timedelta
from time import sleep
from sys import stdout
#These values will be populated by the existing logic
ip_found = -1
port_found = -1
#This is some IP address to be blocked
s_addr = ""
#Sorted List of IP addresses
ip_list = []
while True:
#Create temporary list
tmp_list = ip_list[:]
if (ip_found == -1 and port_found == -1):
tmp_list.append({'ip_address': s_addr, 'blocked_at': datetime.now()})
ip_list = sorted(tmp_list, key=lambda x: x['blocked_at'])
os.system("iptables -A INPUT -s "+str(s_addr)+" -j DROP")
print(str(s_addr) + " was a malcious IP and it is blocked")
else:
print("Not a malcious IP")
unblock_time = datetime.now()
#Keep unblocking all IPs which have been blocked for 1 hour or more
while (ip_list[0]["blocked_at"] + timedelta(hours = 1) < unblock_time):
print(ip_list[0]["blocked_at"])
unblock_ip = ip_list.pop(0)
#Implement command to unblock IP
os.system("-------- command to unblock IP --------")
print("Unblocked IP " + unblock_ip['ip_address'])
#if needed output may be flushed to stdout
stdout.flush()
#sleep for 1 second
sleep(1)
- You need to write the command to unblock the IP Address
- Please use this as a starting point and not as a copy-paste solution!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.