人生第一份python脚本 ---- 遍历文件夹中文件,删除特定文件中的一行代码
2013-10-11 16:00
1091 查看
因为要替老师管理一个服务器,然后发现服务器中的一个网页模版文件被植入了 一行恶意代码。 因为是模版文件,所以很多生成的静态 html文件都含有这段恶意代码,人工修改太过麻烦,而且网站后台管理又没有提供这个功能,所以就看着各种资料写下了下面这个简陋的 脚本处理文件。
Oh Year,避免纯手工删除代码的悲剧~
没有用到正则匹配那些模版。。只是简单字符串相等就完成了。
#search.py
这个表示要修改的文件名后缀
这个表示要删除的恶意代码
使用时就这样打
search.py是这个脚本的名字,dir是要修改的目录
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"
search.py是这个脚本的名字,dir是要修改的目录
相关文章推荐
- python遍历文件夹并删除特定格式文件的示例
- python遍历文件夹并删除特定格式文件的示例
- Python遍历文件夹,删除空文件夹,过滤特定大小和格式的文件
- Python linecache.getline()读取文件中特定一行的脚本
- python2.7删除文件夹和删除文件代码实例
- python 删除目录下特定文件夹和文件
- Python实现删除时保留特定文件夹和文件的示例
- Python:统计特定文件夹中,特定文件代码行数的小程序
- Python实现删除时保留特定文件夹和文件
- Python遍历文件夹和读写文件的实现代码
- python 脚本(获取指定文件夹、指定文件格式、的代码行数、注释行数)
- windows下用c++和python遍历目录下的文件夹并删除所有文件名为xx的文件
- Python实现删除当前目录下除当前脚本以外的文件和文件夹实例
- Python linecache.getline()读取文件中特定一行的脚本
- python 遍历文件夹文件代码
- python3 遍历删除特定后缀名文件的方法
- python 脚本(获取指定文件夹、指定文件格式、的代码行数、注释行数)
- Python实现递归遍历文件夹并删除文件
- Python实现删除当前目录下除当前脚本以外的文件和文件夹实例
- Python遍历文件夹和读写文件的实现代码