检测网站挂马程序(Python)

系统管理员通常从svn/git中检索代码,部署站点后通常首先会生成该站点所有文件的MD5值,如果上线后网站页面内容被篡改(如挂马)等,可以比对之前生成MD5值快速查找去那些文件被更改,为了使系统管理员第一时间发现,可结合crontab或nagios等工具。

程序测试如下:

  1. # python check_change.py
  2.     Usage: python check_change.py update /home/wwwroot
  3.            python check_change.py check /home/wwwroot
  4. # python check_change.py update /data/www #生成站点的md5值
  5. # echo ‘ ‘ > /data/www/sitemap.html #测试清空文件
  6. # rm -rf /data/www/sitemap.xml #测试删除文件
  7. # python check_change.py check /data/www  #查找那些文件被篡改
  8. /data/www/sitemap.xml
  9. /data/www/sitemap.html

代码如下(check_change.py):

  1. #!/usr/bin/env python  
  2.   
  3. import os,sys,subprocess  
  4.   
  5. def update(path):  
  6.     f = open(file,’w’)  
  7.     for root,dirs,files in os.walk(path):  
  8.         for name in files:  
  9.             line = os.path.join(root, name)  
  10.             (stdin,stderr) = subprocess.Popen([‘md5sum’,line],stdout=subprocess.PIPE).communicate()  
  11.             f.write(stdin)  
  12.     f.close()  
  13.   
  14. def check(path):  
  15.     f = open(file,’r’)  
  16.     for line in f:  
  17.         check_ok = “””echo ‘%s’ | md5sum -c > /dev/null 2>&1″”” % line  
  18.         #print check_ok  
  19.         if not subprocess.call(check_ok, shell = True) == 0:  
  20.             abnormal = line.split()  
  21.             print abnormal[1]  
  22.     f.close()  
  23.   
  24. def Usage():  
  25.     print ”’ 
  26.     Usage: python %s update /home/wwwroot 
  27.            python %s check /home/wwwroot 
  28.     ”’ % (sys.argv[0],sys.argv[0])  
  29.     sys.exit()  
  30.   
  31. if len(sys.argv) != 3:  
  32.     Usage()  
  33.   
  34. file = ‘file.key’  
  35. model = sys.argv[1]  
  36. path = sys.argv[2]  
  37.   
  38. if os.path.exists(path) == False:  
  39.     print “\033[;31mThe directory or file does not exist\033[0m”  
  40.     sys.exit()  
  41. elif model == ‘update‘:  
  42.     update(path)  
  43. elif model == ‘check’:  
  44.     check(path)  
  45. else:  
  46.     Usage()  
Fri Oct 25 11:02:44 CST 2013

【AD】炭云:768元/年/1GB内存/20GB SSD空间/2TB流量/500Mbps-1Gbps端口/独立IPv4/KVM/广州移动

【AD】美国洛杉矶CN2 VPS/香港CN2 VPS/日本CN2 VPS推荐,延迟低、稳定性高、免费备份_搬瓦工vps