Python在特定时间删除iptables规则

2024-05-22 01:16:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个基于Python的守护进程,它基于特定参数阻止恶意ip。现在,我想在1小时后自动解除阻止(删除规则)IP,但不确定如何在代码中使用计时器/调度程序模块。在

我知道其他方法可以是:

  1. 失败2ban
  2. ipset超时
  3. iptables-m-recent--seconds开关
  4. cron作业

但我有局限性,不能使用上述替代方法。在

我的主代码在WHILE(1)循环中运行,因此它阻塞了IP。如何在python代码中创建一个并行模块/函数来执行IPTABLES -D命令来删除ip?每个IP都有自己的特定时间来解锁。在

例如

  1. IP1---01:00:00封锁---应在02:00:00解锁
  2. IP2---01:10:00封锁---应在02:10:00解锁
  3. IP3---01:10:10封锁---应在02:10:10解锁

更新:

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")

Tags: and方法代码ipiptables参数进程规则
1条回答
网友
1楼 · 发布于 2024-05-22 01:16:23

从逻辑上讲,您可以尝试以下步骤:

  1. 将被阻止的IP放入队列中;按时间顺序
  2. 每秒钟检查一次队列
  3. 解锁相关项目并将其出列

You may schedule the dequeue process to run when the first item from the queue is to be removed or unblocked.

如果您想在模块中使用相同的逻辑,那么可以尝试以下操作:

while(1):
    queue(List of IPs)
    dequeue()
    sleep(1000) # sleep for 1 second

更新

根据您提供的代码和我的理解,我可以建议实现以下内容:

^{pr2}$
  • 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!

相关问题 更多 >