我的Python字典攻击代码无任何输出,请求技术排查
问题排查与修复
你的代码无法输出结果主要有以下几个问题,下面逐一说明并给出修复后的代码:
核心问题分析
1. 缺少输出语句
代码中仅构造了结果字符串,但未使用 print() 函数将内容输出到控制台。例如:
(f"found math for the hashed value /n")
这行代码只是创建了字符串对象,没有执行任何输出操作,因此你看不到任何结果。
2. Hashlib 输入类型错误(Python 3 环境)
Python 3 中 hashlib.md5() 要求传入字节类型数据,直接传入字符串会抛出 TypeError,导致程序中断(若未捕获异常,错误信息可能不会显示)。
3. Python 版本兼容性问题
raw_input() 是 Python 2 的语法,若在 Python 3 环境运行会直接抛出 NameError,程序无法执行后续逻辑。Python 3 应使用 input()。
4. 拼写与语法错误
- 变量名拼写错误:
recovered_passvord→recovered_password(多了一个 'v') - 单词拼写错误:
found math→found match - 换行符错误:
/n→\n(正确转义换行符为反斜杠) - 无用导入:
import csv和from sqlite3 import register_converter未被使用,可移除。
修复后的代码
import hashlib def dictionary_attack(password_hash): dictionary = {"letmein", "password", "12345", "football"} # 修正"fotball"拼写错误 password_found = False recovered_password = "" # 初始化变量,避免未定义异常 for dictionary_value in dictionary: # 编码为字节类型,适配Python 3 hashed_value = hashlib.md5(dictionary_value.encode('utf-8')).hexdigest() if hashed_value == password_hash: password_found = True recovered_password = dictionary_value break # 找到匹配后立即退出循环,提升效率 if password_found: print(f"Found match for the hashed value:\n") print(f"Password recovered: {recovered_password}") else: print("Password was not found") def main(): # Python 3 使用input(),若为Python 2可换回raw_input() password_hash = input("Enter hashed value: ") dictionary_attack(password_hash) if __name__ == "__main__": main()
额外优化说明
- 添加
break语句:找到匹配密码后立即退出循环,无需遍历剩余字典项,提升执行效率。 - 初始化
recovered_password:避免逻辑错误导致变量未赋值的NameError。 - 修正字典中 "fotball" 的拼写错误,防止因拼写问题漏过正确密码。
内容的提问来源于stack exchange,提问作者Shirin Nazarpooe
相关产品推荐
相关产品推荐

