Python 中的简单用户名和密码应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15846407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:09:47  来源:igfitidea点击:

Simple username and password application in Python

pythonpython-2.7

提问by

I'm trying to build a simple login and password application using a dictionary. It works fine except the part where it checks if the login matches the password (in the bottom where it says "Login successful!").

我正在尝试使用字典构建一个简单的登录名和密码应用程序。除了检查登录名是否与密码匹配的部分(在底部显示“登录成功!”)之外,它工作正常。

If I were to create login 'a' and password 'b', and then create login 'b' and password 'a', it would log me in if I tried to log in with login 'a' and password 'a'. It just checks if those characters exist somewhere in the dictionary, but not if they are a pair.

如果我要创建登录名“a”和密码“b”,然后创建登录名“b”和密码“a”,如果我尝试使用登录名“a”和密码“a”登录,它就会登录。它只是检查这些字符是否存在于字典中的某处,而不是它们是否是一对。

Any suggestions how to fix this?

任何建议如何解决这个问题?

users = {}
status = ""

while status != "q":
    status = raw_input("Are you a registered user? y/n? Press q to quit: ")  

    if status == "n": #create new login
         createLogin = raw_input("Create login name: ")

         if createLogin in users: # check if login name exist in the dictionary
             print "Login name already exist!\n"
         else:
             createPassw = raw_input("Create password: ")
             users[createLogin] = createPassw # add login and password
             print("\nUser created!\n")     

    elif status == "y": #login the user
        login = raw_input("Enter login name: ")

        if login in users:
           passw = raw_input("Enter password: ")
           print

           if login in users and passw in users: # login matches password
               print "Login successful!\n"

        else:
            print
            print("User doesn't exist!\n")

Edit

编辑

Now that this is working, I'm trying to divide the application to three functions, for readability purposes. It works, except that I get infinite loop.

现在这正在起作用,为了便于阅读,我试图将应用程序划分为三个功能。它有效,除了我得到无限循环。

Any suggestions why?

任何建议为什么?

users = {}
status = ""

def displayMenu():
    status = raw_input("Are you a registered user? y/n? Press q to quit: ")  
    if status == "y":
        oldUser()
    elif status == "n":
        newUser()

def newUser():
    createLogin = raw_input("Create login name: ")

    if createLogin in users: # check if login name exists
        print "\nLogin name already exist!\n"
    else:
        createPassw = raw_input("Create password: ")
        users[createLogin] = createPassw # add login and password
        print("\nUser created!\n")     

def oldUser():
    login = raw_input("Enter login name: ")
    passw = raw_input("Enter password: ")

    # check if user exists and login matches password
    if login in users and users[login] == passw: 
        print "\nLogin successful!\n"
    else:
        print "\nUser doesn't exist or wrong password!\n"

while status != "q":            
    displayMenu()

采纳答案by Jared

Right now you are checking if the given password, passw, matches any keysin users(not right). You need to see if the password entered matches that particular user's password. Since you have already checked if the username exists in the dictionary's keys you don't have to check again, so try something like:

现在你正在检查,如果给定的密码,passw,匹配任何users(不正确)。您需要查看输入的密码是否与该特定用户的密码匹配。由于您已经检查了用户名是否存在于字典的键中,因此您不必再次检查,因此请尝试以下操作:

if passw == users[login]:
    print "Login successful!\n"

EDIT:

编辑:

For your updated code, I'm going to assume by "infinite loop" you mean that you cannot use qto exit the program. It's because when you're inside displayMenu, you save user input in a local variablenamed status. This local variable does notrefer to the same statuswhere you are checking,

对于您更新的代码,我将通过“无限循环”假设您的意思是您无法q退出程序。这是因为当你在里面时displayMenu,你将用户输入保存在一个名为的局部变量中status。这个局部变量并不指向同一个status地方要检查,

while status != "q": 

In other words, you are using the variable statusin two different scopes(changing the inner scope does not change the outer).

换句话说,您status两个不同的作用域中使用变量(改变内部作用域不会改变外部作用域)。

There are many ways to fix this, one of which would be changing,

有很多方法可以解决这个问题,其中之一是改变,

while status != "q":
    status = displayMenu()

And adding a return statement at the end of displayMenulike so,

并在displayMenu像这样的末尾添加一个 return 语句,

return status

By doing this, you are saving the new value of statusfrom local scope of displayMenuto global scope of your script so that the whileloop can work properly.

通过这样做,您将保存statusdisplayMenu脚本的本地范围到全局范围的新值,以便while循环可以正常工作。

Another way would be to add this line to the beginning of displayMenu,

另一种方法是将此行添加到的开头displayMenu

global status

This tells Python that statuswithin displayMenurefers to the global scoped statusvariable and not a new local scoped one.

这告诉 PythonstatusdisplayMenu指的是全局范围status变量,而不是新的局部范围变量。

回答by Sheng

change

改变

if login in users and passw in users: # login matches password

to

if users[login] == passw: # login matches password

Besides, you should not tell the hackers that "User doesn't exist!". A better solution is to tell a generall reason like: "User doesn't exist or password error!"

此外,您不应该告诉黑客“用户不存在!”。更好的解决方案是说出一般原因,例如:“用户不存在或密码错误!”

回答by Carlos Neves

Please encrypt you passwords in database if you go put this online. Good work.

如果你把它放在网上,请在数据库中加密你的密码。干得好。

import md5
import sys
# i already made an md5 hash of the password: PASSWORD
password = "319f4d26e3c536b5dd871bb2c52e3178" 
def checkPassword():
    for key in range(3):
        #get the key
        p = raw_input("Enter the password >>")
        #make an md5 object
        mdpass = md5.new(p)
        #hexdigest returns a string of the encrypted password
        if mdpass.hexdigest() == password:
            #password correct
            return True
        else:
            print 'wrong password, try again'
    print 'you have failed'
    return False

def main():
    if checkPassword():
        print "Your in"
        #continue to do stuff

    else:
        sys.exit()
if __name__ == '__main__':
    main()

回答by pymaster

usrname = raw_input('username   :     ')
if usrname == 'username' :
    print 'Now type password '

else :
    print 'please try another user name .this user name is incorrect'


pasword = raw_input ('password     :    ')
if pasword  == 'password' :
    print ' accesses granted '
    print ' accesses granted '
    print ' accesses granted '
    print ' accesses granted '
    print 'this service is temporarily unavailable'

else :
    print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
    print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
    print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
    exit()

回答by Steeve Davis

This is a very simple one based on the one earlier for a single user with improved grammar and bug fixes:

这是一个非常简单的方法,基于之前为单个用户提供的语法和错误修复:

print("Steam Security Software ?")
print("-------------------------")
print("<<<<<<<<<Welcome>>>>>>>>>")
username = input("Username:")
if username == "username" :
    print ("Now type password")

else :
    print ("please try another user name. This user name is incorrect")


password = input ("Password:")
if password  == "password" :
    print ("ACCESS  GRANTED")
    print ("<<Welcome Admin>>")
    #continue for thins like opening webpages or hidden files for access

else :
    print ("INTRUDER ALERT !!!!" , "SYSTEM LOCKED")
    exit()