继上文,如果网页中被插入了恶意代码,会导致弹窗等插件一直弹出,影响我们的使用,由此,可以使用python代码解决这个问题。
例如,网页代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script language="JavaScript">{
var xmldoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
xmldoc.load("<root><child></child></root>");
alert(xmldoc.xml);
}
</script>
<script language="JavaScript">
alert("hello world");
</script>
</body>
</html>
其中被插入的恶意代码为:
<script language="JavaScript">{
var xmldoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
xmldoc.load("<root><child></child></root>");
alert(xmldoc.xml);
}
</script>
<script language="JavaScript">
alert("hello world");
</script>
网页显示:
要对这整个网页代码进行删除,则需要定位代码中的恶意代码标签,每一句定位准确,就可以准确的删除恶意代码,例如,定位每一句标签的python代码为:
import os
#获取templaters目录的路径
curr_path=os.getcwd() #获取当前目录
templaters_path=os.path.join(curr_path,'templaters') #使用join函数拼接得到tempalters目录路径
#使用os.listdir()函数获取指定目录中的文件和文件夹
all_files=os.listdir(templaters_path)
#遍历所有文件
for file in all_files:
path=os.path.join(templaters_path,file) #使用join函数拼接得到file的完整路径
if os.path.isfile(path): #判断是否是文件os.path.isfile(path),判断是否是目录os.path.isdir(path)
openfile=open(path,'r') #以只读方式打开文件
lines=openfile.readlines() #读取该文件的所有行
rule1='<script language="JavaScript">{'
rule2=' var xmldoc = new ActiveXObject("MSXML2.DOMDocument.3.0");'
rule3=' xmldoc.load("<root><child></child></root>");'
rule4=' alert(xmldoc.xml);'
rule5='}'
rule6='</script>'
new_lines=[] #创建空列表
tmp=[]
flag=0
for line in lines: #遍历文件的所有行
if rule1 in line: #如果rule变量内的内容存在于line,则跳出该轮循环执行下一轮循环
tmp.append(line)
flag=1
elif rule2 in line and flag==1:
tmp.append(line)
flag=2
elif rule3 in line and flag==2:
tmp.append(line)
flag=3
elif rule4 in line and flag==3:
tmp.append(line)
flag=4
elif rule5 in line and flag==4:
tmp.append(line)
flag=5
elif rule6 in line and flag==5:
tmp.append(line)
tmp=[]
flag=6
elif flag!=6:
new_lines.extend(tmp)
new_lines.append(line)
flag=0
tmp=[]
break
else: #如果不存在,则将读取的内容写入到列表中
new_lines.append(line)
openfile.close() #关闭文件
writefile=open(path,'w')
writefile.writelines(new_lines) #将列表中的内容写入到文件
writefile.close() #关闭文件
运行代码,查看运行后的结果:
则,恶意代码被删除。