Skip to content

Instantly share code, notes, and snippets.

@spnow
Forked from songmw90/iptables_mysql.py
Created January 5, 2017 01:11
Show Gist options
  • Select an option

  • Save spnow/73c731ae4b614a482bccc10eed516f38 to your computer and use it in GitHub Desktop.

Select an option

Save spnow/73c731ae4b614a482bccc10eed516f38 to your computer and use it in GitHub Desktop.
Monitor mysql-error.log / added iptables to block ip
#!/usr/bin/env python
# -*- coding: utf8 -*-
import re
from subprocess import call
path = "/var/log/mysql/"
log = "error.log"
logContents = ""
excludeText = "localhost 110.15.211.94 175.207.12.146"
with open("{}{}".format(path,log)) as f:
logContents = f.read()
extractedIP = {}
for ip in re.findall( r'\'?\'@\'[0-9]+(?:\.[0-9]+){3}\'', logContents):
ip = ip.replace('@','').replace('\'','')
try:
if type(extractedIP[ip]):
extractedIP[ip] = extractedIP[ip] + 1
except:
extractedIP[ip] = 1
for index in extractedIP:
if extractedIP[index] > 2 and index not in excludeText:
call("iptables -A INPUT -s {} -j DROP".format(index), shell=True)
f = open("{}{}".format(path,"bkup.log"),"ab")
f.write(logContents)
f.close()
f = open("{}{}".format(path,log),"w")
f.write('')
f.close()
call("iptables-save > /opt/iptables.backup", shell=True)
print "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment