I have a quick question as i just can't get my script to work. The problem is everytime i run my script when the first iteration it blocks the ip and adds the ip to a list, the second time it runs it SHOULD skip this ip and print: this ip has already been blacklisted. But what happens is it again blocks the ip, thus clogging my iptables rules list. Any suggestions on what i'm doing wrong?
import subprocess
import os
from time import sleep
def BlockIP():
output = subprocess.getoutput("/usr/bin/netstat -pnut | /usr/bin/grep 443")
with open("netstat.txt", "w") as f:
f.write(output)
with open("netstat.txt", "r") as f:
for x in f.readlines():
x = x.rsplit()
iplist = []
ip1 = x[4].split(":")[0]
if int(x[2]) > 10000:
ip = x[4].split(":")[0]
if ip in iplist:
print("IP: " + ip + " already blacklisted. Skipping...")
else:
print(ip + " Send-Q: " + x[2] + " - Applying iptables rule.")
os.system("/usr/sbin/iptables -I INPUT -s " + ip + " -j DROP")
iplist.append(ip)
def main():
while True:
BlockIP()
if __name__ == "__main__":
main()
73.xxx Send-Q: 65540 - Applying iptables rule. (This is the output it produces)
73.xxx Send-Q: 65540 - Applying iptables rule.
73.xxx Send-Q: 65540 - Applying iptables rule.
73.xxx Send-Q: 65540 - Applying iptables rule.
73.xxx Send-Q: 65540 - Applying iptables rule.