Advertisement
Guest User

Untitled

a guest
Jan 28th, 2014
407
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.00 KB | None | 0 0
  1. import select
  2.  
  3. from sh import tail
  4.  
  5. # Connection to Mediawiki database.
  6. dbconnection = mysql.connector.connect(user='dbuser', password='dbpassword', database='mediawikidb')
  7.  
  8. # Non-interactive Mysql cmd line to pipe commands through.
  9. dbcursor = dbconnection.cursor()
  10.  
  11. # Blocklist Mysql query.
  12. ipblocks_query = ("select ipb_address from ipblocks where ipb_address=%s")
  13. # User Mysql query.
  14. user_query = ("select user_name from user where user_name=%s")
  15.  
  16. table = iptc.Table(iptc.Table.FILTER)
  17. rule = iptc.Rule()
  18. chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
  19.  
  20. # Iterate through each line in log-file.
  21. f = subprocess.Popen(['tail','-F',"/var/log/nginx.log"],\
  22. stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  23. p = select.poll()
  24. p.register(f.stdout)
  25.  
  26. while True:
  27. if p.poll(1):
  28. line = f.stdout.readline()
  29. # Select lines which contain an IP address at line start AND user talk page reference.
  30. if re.findall("^\d+\.\d+\.\d+\.\d+", line) and re.findall("User:\w+", line):
  31. found = 0
  32. # Replace line with IP address and user reference only.
  33. line = re.findall("^\d+\.\d+\.\d+.\d+|User:\w+", line)
  34. # Check if ip address is already blocked by iptables.
  35. for chain in table.chains:
  36. for rule in chain.rules:
  37. if re.sub("/255.255.255.255", "", rule.src) == line[0]:
  38. found = 1
  39. break
  40. if found == 0:
  41. line[1] = re.sub("User:", "", line[1])
  42. line[1] = re.sub("_"," ", line[1])
  43. # Query user against ipblocks table.
  44. dbcursor.execute(ipblocks_query, (line[1],))
  45. print (line[1])
  46. row = dbcursor.fetchone()
  47. # If user exists in ipblocks table.
  48. if row is not None:
  49. print ("Is banned!")
  50. # If not found add to iptables.
  51. rule.in_interface = "eth0"
  52. rule.src = line[0]
  53. t = rule.create_target("DROP")
  54. chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
  55. chain.insert_rule(rule)
  56. print ("Blocking IP address with iptables")
  57. print ("-")
  58. # Check if user exists in user table.
  59. else:
  60. dbcursor.execute(user_query, (line[1],))
  61. row = dbcursor.fetchone()
  62. if row is not None:
  63. print ("Is not banned!")
  64. print ("-")
  65. # If user doesn't exist block IP with iptables..
  66. else:
  67. print ("Does not exist!")
  68. rule.in_interface = "eth0"
  69. rule.src = line[0]
  70. t = rule.create_target("DROP")
  71. chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
  72. chain.insert_rule(rule)
  73. print ("Blocking IP address with iptables")
  74. print ("-")
  75. time.sleep(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement