Ver Fonte

Fixed unblock error when iptables fails

  iptables fails and throws a CalledProcessError which was killing our program... now we have output but at least the program continues to run.
root há 4 anos atrás
pai
commit
3840fc7f2c
1 ficheiros alterados com 20 adições e 10 exclusões
  1. 20 10
      failUser.py

+ 20 - 10
failUser.py

@@ -2,7 +2,7 @@
 from json import loads, dumps
 from json.decoder import JSONDecodeError
 import pendulum
-from subprocess import run, PIPE
+from subprocess import run, PIPE, CalledProcessError
 from os.path import exists, join
 from pyinotify import WatchManager, Notifier, ProcessEvent
 from pyinotify import IN_MODIFY, IN_DELETE, IN_MOVE_SELF, IN_CREATE
@@ -27,26 +27,35 @@ dirmask = IN_MODIFY | IN_DELETE | IN_MOVE_SELF | IN_CREATE
 
 def blocker(ip):
     # Utility function to block given ip as string
-    #run(["iptables", "-I", "DOCKER-USER", "-i", "eth0", "-s", ip, "-j", "DROP"], stdout=PIPE, check=True)
-    print("iptables -I DOCKER-USER -i eth0 -s {0} -j DROP".format(ip))
+    run(["iptables", "-I", "DOCKER-USER", "-i", "eth0", "-s", ip, "-j", "DROP"], stdout=PIPE, check=True)
+    #print("iptables -I DOCKER-USER -i eth0 -s {0} -j DROP".format(ip))
 
 def unblocker(ip):
     # Utility function to unblock given ip as string
-    #run(["iptables", "-D", "DOCKER-USER", "-i", "eth0", "-s", ip, "-j", "DROP"], stdout=PIPE, check=True)
-    print("iptables -D DOCKER-USER -i eth0 -s {0} -j DROP".format(ip))
+    try:
+        run(["iptables", "-D", "DOCKER-USER", "-i", "eth0", "-s", ip, "-j", "DROP"], stdout=PIPE, check=True)
+    except CalledProcessError:
+        pass
+    #print("iptables -D DOCKER-USER -i eth0 -s {0} -j DROP".format(ip))
 
 def is_bad(line):
+    global bad_users
     # Given line, attempt to parse... then is there a issue with it
     # Returns a python dict with ip and time in log
     if line: # Do we actually have something?
         try:
             j = loads(line)
             #if j["msg"] == "Attempt to login with banned username":
-            if j["username"] in bad_users:
-                r = {}
-                r["ip"] = "{0}".format(j["ip"][7:])
-                r["time"] = j["time"]
-                return r
+            try:
+                if j["username"] in bad_users or j["msg"] == "Attempt to login with banned username":
+                    if j["username"] not in bad_users:
+                        bad_users.append(j["username"])
+                    r = {}
+                    r["ip"] = "{0}".format(j["ip"][7:])
+                    r["time"] = j["time"]
+                    return r
+            except KeyError:
+                pass
         except JSONDecodeError:
             log.error("Failed to decode line, '{0}'".format(line))
 
@@ -116,6 +125,7 @@ target.close()
 
 # Update config
 myConfig["last_unblock"] = last.to_atom_string()
+myConfig["bad_users"] = bad_users
 save_config(myConfig)
 
 exit(0)