python实时监控访问日志
需求:对nginx的访问日志进行实时的检查,如果恶意访问则添加到iptables列表中进行拒绝设置。//访问日志的格式为默认格式
***正则表达式的zz_r变量中的关键字自行增减。目前在使用中.......
1 import os,sys 2 import subprocess 3 import re 4 5 6 #定义实时监控模块 7 def monitor_log(access_log): 8 print('monitor access log :%s'%access_log) 9 #实时读取访问日志 10 popen = subprocess.Popen('tail -f '+access_log,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 11 12 #进行循环匹配 13 while True: 14 zz_r = re.compile("\.mdb|\.inc|\.sql|\.config|\.bak|\.svn|info\.php|\.bak|wwwroot|wp-login \ 15 |gf_admin|struts|jmx-console|\.ini|\.conf|%2Fpasswd|passwd|\.xml|\.exe|execute|1.asp|admin\.aspx \ 16 |dircontext|phpmyadmin|order%20by|%20where%20|%20union%20|%2ctable_name%20|%27exec \ 17 |select%20|%20and%201=1|%2csleep|%20and%201=2|div.aps|xiaoma.jsp|tom.jsp|py.jsp \ 18 |context\.get|getwriter|information_schema|/k8cmd|ver007.jsp|ver008.jsp|ver007|ver008|%if|\.aar|cmdshell" ) 19 line=popen.stdout.readline().strip() 20 new_line=zz_r.search(line.lower()) 21 #print("----->",new_line) 22 #判断是否有匹配到,如果有匹配则将IP添加到iptables做drop处理 23 if new_line: 24 #提取恶意IP 25 zz = re.compile('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}') 26 #line_ip = zz.search((line.split(':')[1].split(','))[0]).group() 27 line_ip = zz.search(line).group() 28 #将IP添加到iptables列表中 29 os.system("iptables -I INPUT -s %s -j DROP" %line_ip) 30 print('the fuck ip [%s] is added to iptables'%line_ip) 31 32 33 if __name__=='__main__': 34 #判断程序启动是否有三个参,如果是三个参则将第三个参数传进monitor_log函数里 35 if len(sys.argv) == 3: 36 monitor_log(sys.argv[2]) 37 else: 38 msg=''' 39 input argv is wrong 40 example: \033[31;1m python sec_monitor -f access.log\033[0m 41 ''' 42 print(msg)