Consider scenario on large production system, when a new table is created or an alter table is triggered then we may need to notify few users. We came across a same scenario when the table schema or new table created, we need to notify few users.

Assumption:

  1. Mysql general query log is enabled and the path is /var/lib/mysql/mysql-general.log. If not enabled, please enable. If the path is different, modify the script accordingly.
#!/usr/bin/python
import re,os,time
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from subprocess import Popen, PIPE
pa1=re.compile("alter table")
pa2=re.compile("create table")
os.system('touch /tmp/output')
fopen=open("/var/lib/mysql/mysql-general.log","r");
for log in fopen.readlines():
    columns=log.split('\t')
    if "show create table" in columns[-1].lower():
        continue
    if pa1.pattern in columns[-1].lower() or  pa2.pattern in (columns[-1].lower()):
        columns=log.split('\t')
        output=open('/tmp/output','a+')
        output.write("\n-------------------")
        output.write("\n*%s" %(columns[-1]))
        output.write("-------------------")
        output.close()
fopen.close();
if (os.stat("/tmp/output").st_size != 0):
        with file('/tmp/output','r') as original: data=original.read()
        with file('/tmp/output','w') as modified: modified.write("Below Alter/Create Queries have been Run\n" +time.strftime("%c") + data)
        so=open('/tmp/output','r')
        mysqlaudit=MIMEText(so.read());
        mysqlaudit["From"] = "mysqlauditreport@domain.tld"
        mysqlaudit["To"] = "user@domain.tld"
        mysqlaudit["Subject"] = "Mysql Audit Report"
        p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
        p.communicate(mysqlaudit.as_string())
        so.close()
os.remove('/tmp/output');

Leave a Reply