您的位置:首页 > 编程语言 > Python开发

人生第一份python脚本 ---- 遍历文件夹中文件,删除特定文件中的一行代码

2013-10-11 16:00 1091 查看
因为要替老师管理一个服务器,然后发现服务器中的一个网页模版文件被植入了 一行恶意代码。  因为是模版文件,所以很多生成的静态 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"


search.py是这个脚本的名字,dir是要修改的目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息