2012-12-19 61 views
2

我正在編寫我的第一個用於查找和刪除惡意軟件js-code的服務器腳本,但是我從一開始就找不到一個簡單的方法來重寫現有文件,而不是最後。從頭開始編寫文件

# -*- 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() 

回答

5

f.seek(0)在寫之前。 f.truncate()然後切斷任何額外的文本。

+0

是的,我知道。但是,也許使用錯誤,如果文件包含更多文本(在我的情況下 - 必然) - 它加入到替換文本。例如:文件包含「AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA」,f.seek(0)f.write(「aa」)它將在文件中:「aaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA」,而不僅僅是「aa」。 – Rukomoynikov

+0

你忘了「f.truncate()」 – Goranek

+1

它的工作原理,它的工作原理!非常感謝) – Rukomoynikov

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) 
+0

這是錯誤的,你刪除了text = f.read(),並用「w」你不能讀取()。 kindall的答案是正確的 – Goranek

+1

我提出了一種不同的方法:通過讀取文件並遍歷它的行,或者讀取整個內容,然後只搜索整個字符串(實際上,這可能是最好的方法)。然後,寫入新打開的文件('w'覆蓋其內容)。 – snurre

+0

對不起,你是對的,我沒有看到readlines的代碼。仍然你沒有任何需要打開文件兩次 – Goranek