用于循环功能

时间:2017-02-08 07:33:32

标签: python python-3.x for-loop brute-force

我试图写一个暴力python脚本。我按照本教程link进行了修改,并根据自己的需要对其进行了修改。大多数代码工作正常,除了输出只有一个输出而不是26

file = args.imp
MAX_KEY_SIZE = 26
message = open(file)

def getKey():
    key = 0
    print("Enter the key number (1-%s)" % (MAX_KEY_SIZE))
    key = int(input())
    while True:
            if (key >= 1 and key <= MAX_KEY_SIZE):
                    return key

def decode(message, key):
    translated = ''


    for symbol in message.read():

            num = ord(symbol)
            num += key

            if num > ord('Z'):
                    num -= 26
            elif num < ord('A'):
                    num += 26
            translated += chr(num)
    return translated


key = getKey()

for k in range(1, MAX_KEY_SIZE + 1):
    print(k, decode(message, key))

输出是:

Enter the key number (1-26)
4
1 BDPWCCONVESDKLOOVACAXKYFJJBGDCSLRRPTYYYIBQNOXLZYHCHCNZCRM
2
3 
4
5
6 etc to 26

2 个答案:

答案 0 :(得分:2)

你不能一次又一次地读取文件。您必须将文件对象的位置设置回到开头。否则,message.read()将返回一个空字符串。添加

message.seek(0)

decode函数的开头。

答案 1 :(得分:1)

一旦调用read(),它将读取整个文件并将读取光标留在文件末尾。当您在这种情况下读取文件时,它将返回''(空字符串)。这就是原因,你只是在第一次迭代时得到输出而且只是空的。

您可以按@schwobaseggl的回答寻找(指向文件开头的光标)。

或者在开始时读取所有文件一次,

message = open(file).read()

# code here

def decode(message, key):
    translated = ''
    for symbol in message:
            num = ord(symbol)
            num += key
            if num > ord('Z'):
                    num -= 26
            elif num < ord('A'):
                    num += 26
            translated += chr(num)
    return translated