密码破解程序遇“list index is out of range”报错及随机函数问题求助
密码破解程序问题修复
核心问题分析
- list index is out of range错误:
randint(0, len(possible))中,列表的最大索引是len(possible)-1,但randint是闭区间取值,会取到等于列表长度的数值,直接导致索引越界。 - 随机猜测逻辑混乱:
- while循环内嵌套的for循环完全多余,会导致单次循环内多次生成猜测,逻辑重叠。
- 未处理密码前导零问题:比如用户输入"0012",转成int后变为12,而随机生成的数字12转成字符串是"12",长度不匹配,永远无法匹配原密码。
- 尝试次数计数错误,没有正确累加每次猜测的次数。
修复步骤
- 修复索引越界:把
randint(0, len(possible))改为randint(0, len(possible)-1),或者直接用choice(possible)随机选取元素,更简洁安全。 - 修正猜测逻辑:
- 移除多余的for循环,仅保留while循环持续猜测直到匹配。
- 将生成的数字转为字符串并补前导零,确保长度和用户输入的密码一致,直接用字符串对比(避免转int丢失前导零)。
- 每次猜测后累加尝试次数,计数逻辑准确。
- 优化输出逻辑:保留清屏的同时,确保每次猜测的信息先打印再清屏,或者根据需求移除清屏方便查看过程。
修复后的完整代码
from random import choice import os u_pwd = input("Enter a password: ") pwd_length = len(u_pwd) # 生成所有可能的密码字符串,补前导零保证长度一致 possible = [str(num).zfill(pwd_length) for num in range(0, 10 ** pwd_length)] outcomes = len(possible) attempts = 0 pw = "" while pw != u_pwd: attempts += 1 pw = choice(possible) print(f"Current guess: {pw}") print("Cracking Password..... Please wait..... ") print(f"Attempt {attempts} of {outcomes}") os.system("cls") # Linux/macOS系统请替换为os.system("clear") print(f"Your password is : {pw}") if attempts < 2: print(f"This password took {attempts} attempt") else: print(f"This password took {attempts} attempts")
暴力遍历版本(无重复猜测)
如果想要避免重复猜测,直接遍历所有可能的密码,效率更高:
import os u_pwd = input("Enter a password: ") pwd_length = len(u_pwd) possible = [str(num).zfill(pwd_length) for num in range(0, 10 ** pwd_length)] outcomes = len(possible) attempts = 0 for pw in possible: attempts += 1 print(f"Current guess: {pw}") print("Cracking Password..... Please wait..... ") print(f"Attempt {attempts} of {outcomes}") os.system("cls") # Linux/macOS系统请替换为os.system("clear") if pw == u_pwd: break print(f"Your password is : {pw}") if attempts < 2: print(f"This password took {attempts} attempt") else: print(f"This password took {attempts} attempts")
内容的提问来源于stack exchange,提问作者Jethro Blemur
相关产品推荐
相关产品推荐

