Система паролей Python с блокировкой после определенного количества попыток - PullRequest
0 голосов
/ 05 сентября 2018

Поэтому я пытаюсь создать систему паролей в Python, в результате чего после определенного количества неправильных попыток пользователю будет заблокирован доступ к нему, скажем, в течение 5 минут. В настоящее время я не уверен, как значения переменных можно сохранить после повторного запуска того же файла, а затем использовать таким образом. Может ли кто-нибудь помочь мне с этим, так как я в настоящее время еще новичок в Python?

Обновление:

После экспериментов с кодом, предоставленным мне Йонасом Вольфом, я доработал свой код до следующего:

def password(): 
    count = 0 
    currentTime = float(time.time()) 
    passwordList = ["something", "password", "qwerty", "m42?Cd", "no"] 
    passwordNum = random.randint(0, 4) 
    password = passwordList[passwordNum] 
    with open("password.txt", "r") as file:
        check = file.readline()
        initialTime = file.readline()
        if initialTime=="":
            initialTime==0
    if int(check)==1 and (currentTime-float(initialTime))<300:
        print("You are still locked")
        print("Please try again in", int(300-(currentTime-float(initialTime))), "seconds.")
        quit()
    print("The randomised password is No.", passwordNum+1) #Prints a string to let the user know which password was randomly selected
    while count<5:
        inp = input("Enter the Password: ")
        if inp==password:
            print("Access Granted")
            print()
            f = open("password.txt", "w")
            f.write("0\n0")
            f.close()
            select()
        elif (count+1)==5:
            print("You have been locked")
            print("Please try again in 5 minutes")
            f = open("password.txt", "w")
            f.write("1\n")
            f.write(str(currentTime))
            f.close()
            quit()
        else:
            count+=1
            print("Incorrect Password")
            print("You have", 5-count, "tries left.")
            continue

Большое спасибо за помощь, которую вы оказали, и за терпение, с которым вы ответили на мои вопросы.

1 Ответ

0 голосов
/ 05 сентября 2018
import YourProgram # this is the program you want to run, if the program runs automaticly when opened then move the import to the part where i wrote YourProgram() and delete the YourPregram() line
import time

pswd = "something"

count = 0

with open("PhysxInit.txt","r") as file:
    file_info = file.readline()
    numa = file_info.count("1")
    count = numa


while True:
    with open("PhysxInit.txt","r") as file:
        file_info = file.readline()
        tima = file.readline()


    inp = input("What is the password:")



    if inp == pswd:

        if tima == "":
            tima = "0"  # this should solve yoúr problem with float convertion however it doesn't make sence that this step should be needed


        if str(file_info[:5]) != "11111" or time.time() > float(tima):
            YourProgram() # this is just meant as the thing you want to do when when granted acces i magined you where blocking acces to a program.
            f = open("PhysxInit.txt", "w")
            f.write("\n")
            f.close()
            break
    else:
        count += 1
        f = open("PhysxInit.txt", "w")
        f.write(("1"*count)+"\n"+str(tima))
        if count == 5:
             f.write(str(time.time()+60*5))
        f.close()

#f = open("PhysxInit.txt", "w")
#f.write("\n")
#f.close()

это работает? просто убедитесь, что у вас есть текстовый файл с именем PhysxInit.txt

после запуска программы и, несколько раз угадав, мой текстовый файл выглядит следующим образом.

11111
1536328469.9134998

это должно выглядеть примерно так, как у меня, хотя цифры могут быть разными.

Чтобы прочитать конкретную строку, как вы просили, вам нужно сделать:

with open("PhysxInit.txt", "r") as f:
    for w,i in enumerate(f):
        if w == #the number line you want:
            # i is now the the line you want, this saves memory space if you open a big file
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...