Last active
March 6, 2017 05:03
-
-
Save songmw90/198e1d5b87ec3226b8ad to your computer and use it in GitHub Desktop.
Monitor mysql-error.log / added iptables to block ip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf8 -*- | |
import re | |
from subprocess import call | |
path = "/var/log/mysql/" | |
log = "error.log" | |
logContents = "" | |
excludeText = "localhost ....." | |
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) | |
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