Python implementation of the detection of the site hanging horse program

  • 2020-04-02 14:27:50
  • OfStack

System administrators often retrieved from the SVN/git code, usually first after deployment site will generate MD5 value of all the files for this site, if online web page content after been tampered with (such as hang a horse), before can compare to generate MD5 value quickly find those documents are changed, in order to make the system administrator for the first time found that can be combined with the crontab or nagios tools, etc.

The program is tested as follows:


# python check_change.py

  Usage: python check_change.py update /home/wwwroot
      python check_change.py check /home/wwwroot

# python check_change.py update /data/www # Generated site md5 value 
# echo ' ' > /data/www/sitemap.html # Test clean file 
# rm -rf /data/www/sitemap.xml # Test delete file 
# python check_change.py check /data/www # Look for files that have been tampered with 
/data/www/sitemap.xml
/data/www/sitemap.html

The code is as follows (check_change.py) :


#!/usr/bin/env python

import os,sys,subprocess

def update(path):
  f = open(file,'w')
  for root,dirs,files in os.walk(path):
    for name in files:
      line = os.path.join(root, name)
      (stdin,stderr) = subprocess.Popen(['md5sum',line],stdout=subprocess.PIPE).communicate()
      f.write(stdin)
  f.close()

def check(path):
  f = open(file,'r')
  for line in f:
    check_ok = """echo '%s' | md5sum -c > /dev/null 2>&1""" % line
    #print check_ok
    if not subprocess.call(check_ok, shell = True) == 0:
      abnormal = line.split()
      print abnormal[1]
  f.close()

def Usage():
  print '''
  Usage: python %s update /home/wwwroot
      python %s check /home/wwwroot
  ''' % (sys.argv[0],sys.argv[0])
  sys.exit()

if len(sys.argv) != 3:
  Usage()

file = 'file.key'
model = sys.argv[1]
path = sys.argv[2]

if os.path.exists(path) == False:
  print "033[;31mThe directory or file does not exist033[0m"
  sys.exit()
elif model == 'update':
  update(path)
elif model == 'check':
  check(path)
else:
  Usage()

Related articles: