人生第一份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"


search.py是这个脚本的名字,dir是要修改的目录


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值