在同一行上打印更新的计数器

问题描述

我有代码

import hashlib

pass_hash = input("Enter MD5 Hash: ")
wordlist = input("Wordlist name: ")

try:
    pass_file = open(wordlist,'r')
except FileNotFoundError:
    print("File not found.")
    quit()


def main():
    counter = 0
    print(f"List count: {str(counter)} Type: alphanum")

    for word in pass_file:
        encoded_word = word.encode('utf-8')
        digest = hashlib.md5(encoded_word.strip()).hexdigest()

        counter += 1

        if digest == pass_hash:
            print(f"Password found: {word}")
            break
    else:
        print("Password not found")


main()

我正在尝试打印计数器的当前阶段,例如在同一行上将1替换为2,然后替换为3,以此类推,直到密码哈希被破解为止。就像加载栏一样,到目前为止已经迭代了数字。

解决方法

使用字符串串联:

stringToPrint = "List count: " + str(counter) + " Type: alphanum"
print(stringToPrint)
,

您可以使用回车符来完成此操作:

counter = 0
for word in pass_file:
    sys.stdout.write(f"\rList count: {str(counter)} Type: alphanum")
    sys.stdout.flush()
    counter += 1

    encoded_word = word.encode('utf-8')
    digest = hashlib.md5(encoded_word.strip()).hexdigest()

    if digest == pass_hash:
        print(f"\nPassword found: {word}")
        break

您需要刷新stdout流以确保将其写入(通常,输出流将等待大量缓冲区或换行符(\ n)打印出来,因此您需要手动刷新。

您还需要在找到密码后添加一个换行符,因为在编写计数器时不会包含一个换行符。