人生第一份python脚本 - 遍历文件夹汉语言件,删除特定文件中的一行代码
人生第一份python脚本 ---- 遍历文件夹中文件,删除特定文件中的一行代码
使用时就这样打
因为要替老师管理一个服务器,然后发现服务器中的一个网页模版文件被植入了 一行恶意代码。 因为是模版文件,所以很多生成的静态 html文件都含有这段恶意代码,人工修改太过麻烦,而且网站后台管理又没有提供这个功能,所以就看着各种资料写下了下面这个简陋的 脚本处理文件。
Oh Year,避免纯手工删除代码的悲剧~
没有用到正则匹配那些模版。。只是简单字符串相等就完成了。
#search.py
import sys,os,re,stat path=r'/Users/ipqhjjybj/Desktop/py_source/tests' find_str='<div class="centerd linksytle"><a href="http://www.qvod123.com">qvod</a></div>\r\n' filterType=['html','htm','php','jsp'] #deal file which contains that str def deal(path): #print "deal path "+path fp=open(path,"r") fpContent=fp.readlines() fp.close() fp=open(path,"w") for x in fpContent: if find_str != x: # print "find_str "+find_str fp.write(x) fp.close() #judge file whether contains a destin Str def judge(path): #print "judge "+path #print "sp "+path.split('.')[-1].lower() if path.split('.')[-1].lower() in filterType: fp=open(path,"r") fpContent=fp.readlines() fp.close() for x in fpContent: #print "x "+x #print find_str if find_str == x: deal(path) break return #search all files and folders def search_all_file(path): if os.path.isfile(path): print path try: judge(path) except: pass elif os.path.isdir(path): for item in os.listdir(path): itemsrc=os.path.join(path,item) search_all_file(itemsrc) if len(sys.argv) != 2: print "Usage:python search.py path" sys.exit(1) path=sys.argv[1] print path search_all_file(path)
filterType这个表示要修改的文件名后缀
find_str='<div class="centerd linksytle"><a href="http://www.qvod123.com">qvod</a></div>\r\n'
这个表示要删除的恶意代码
使用时就这样打
python search.py "dir"