test_http_mqtt.py 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. import os
  5. import time
  6. threshold = 120
  7. # 获取前一分钟的结果
  8. date = time.strftime('%Y:%H:%M', time.localtime(time.time()-60))
  9. filename = '/usr/share/nginx/logs/geokon.access.log '
  10. def popen(command):
  11. return os.popen(command).readlines()
  12. def main():
  13. with open('/tmp/ipset.txt', 'a') as f:
  14. f.write('%s: 日志搜索...........\n' % (date))
  15. command = "grep %s %s | awk '{counts[$1]++}; END {for(url in counts) print counts[url], url}'" % (date, filename)
  16. for ip in popen(command):
  17. num, ipaddr = ip.split(' ')
  18. num, ipaddr = int(num), ipaddr.strip() # 第一个值是整型, 第二个值应当去掉空格
  19. if num >= threshold:
  20. if all(popen('ipset list | grep %s' % (ipaddr))): # 如果不为true 那就添加
  21. f.write('每分钟大于%s次 地址: %s 将被禁止访问' % (threshold, ipaddr))
  22. popen('ipset add blacklist %s timeout 3600 &>/dev/null' % (ipaddr))
  23. elif num >= 50:
  24. f.write('访问次数 %s: %s\n' % (num, ipaddr))
  25. f.write('日志搜索结束.................\n\n\n')
  26. if __name__ == '__main__':
  27. main()