0

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.
Anciety
  • 85
  • 2
  • 10
  • 1
    Well, you set `iplist = []` every iteration. If you want to append to a list and have it stick you need to initialize it outside the loop. – theherk Sep 04 '22 at 14:32
  • 1
    Not really the topic of your question, I guess, but saving the `netstat` output in a temporary file and then immediately reading that file seems quite wrong. You want `lines = subprocess.check.output(["netstat", "-pnut"], text=True); for x in lines.splitlines(): if "443" not in x: continue` which also replaces the pipe to `grep` (and thus the [pesky`shell=True`](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess)) with native Python logic. Probably also remember to clean out the temporary files you will have sprinkled across your directories. – tripleee Sep 04 '22 at 14:32
  • Thanks this seems to have fixed it! Wasn't paying attention and looked over it. Also thanks tripleee now it's more efficient. – Anciety Sep 04 '22 at 14:59

0 Answers0