2

我正在编写我的第一个服务器脚本以查找和删除恶意软件 js 代码,但我找不到从头开始重写现有文件的简单方法,而不是在最后。

# -*- coding: utf-8 -*-

import os
import re
import codecs

for dirname, dirnames, filenames in os.walk('.'):
    for filename in filenames:
        f = open(os.path.join(dirname, filename), 'r+b')
        text=f.read()
        if re.search('function g\(\).*\n.*\<script src=\"http://linkfooter.org/linkfooter.js\"></script>\'\);}', text) and os.path.join(filename) != "bezr.py":
            print "starting with " + os.path.join(filename)
            match = re.compile('function g\(\).*\n.*\<script src=\"http://linkfooter.org/linkfooter.js\"></script>\'\);}')
            s = match.sub('', text)
            f.write(s)
        f.close()
        #else:
            #print "in " + os.path.join(dirname, filename) + " none"    
            #f.close()
4

2 回答 2

5

f.seek(0)在你写之前。f.truncate()之后切断任何额外的文本。

于 2012-12-19T20:35:03.580 回答
1
filepath = os.path.join(dirname, filename)
text = file.read(filepath)
if re.search('function g\(\).*\n.*\<script src=\"http://linkfooter.org/linkfooter.js\"></script>\'\);}', line) and os.path.join(filename) != "bezr.py":
    with open(filepath, 'w') as f:
            print "starting with " + os.path.join(filename)
            match = re.compile('function g\(\).*\n.*\<script src=\"http://linkfooter.org/linkfooter.js\"></script>\'\);}')
            s = match.sub('', text)
            f.write(s)
于 2012-12-19T20:44:37.717 回答