当前位置: 代码迷 >> python >> 限制了python中密码的介绍
  详细解决方案

限制了python中密码的介绍

热度:38   发布时间:2023-06-13 16:47:28.0

我的问题是:如何限制错误的密码输入并将其作为功能?

我试图用范围 ,使其

if password == (password1):
    print('Please wait')
    print('Correct, logging in.')
    exit

for password in range(5):
    if password != (password1):
        print('Please wait')
        print('Incorrected, closing program.')

        exit

但它会重复循环5次。

也许您正在寻找与此类似的东西? 我不太确定! 该程序将允许您在退出前输入5次错误的密码。

password1 = "hello"


i=0
while i<=4:
    password = raw_input("Enter password: ")
    if password1 == password:
        print "Welcome"
        break
    else:
        print "Try Again. %d tries left" %(4-i)
        i+=1
else:
    print "oops, you ran out of tries"

使用for .. in range循环,您可以要求用户在循环开始时重新输入,

from getpass import getpass
import random
import sys
import time

def validate_user_password(password, attempts=5):
    for attempts_remaining in reversed(range(attempts)):
        prompt='Please enter the password ({} attempts remaining): '.format(attempts_remaining + 1)
        entry = getpass(prompt=prompt)

        print('Please wait...')

        # Wait random amount between 0.5s and 1s
        time.sleep(random.uniform(0.5, 1))

        if entry == password:
            print('Correct, logging in.')
            return True
        else:
            print('Incorrect password.')
    # All attempts failed
    return False

if __name__ == '__main__':
    password = 'chewbacca'

    if validate_user_password(password):
        print('Admin powers unlocked.  Here are the rocket launch codes: 1-2-3-4-5')
    else:
        print('Closing program.')
        sys.exit(-1)

注意:getpass内置库隐藏了密码输入,因此,从您的肩膀往前看的人看不到您键入的内容。随机睡眠/等待是一种安全措施的示例,该措施有助于防止用户执行以下操作:使用定时攻击(在这种情况下可能不会有所帮助)。