Python 用户名和密码

发布于 2024-10-08 22:53:58 字数 741 浏览 0 评论 0原文

我正在尝试创建一个程序,您可以在其中创建、登录和删除帐户。我制作了 2 个列表,一份包含用户名,一份包含密码。该脚本要求输入,如果您说登录,它会说:

if loginchoice=='login':
    choice = raw_input("What is your username? ")
    choice2 = raw_input("What is your password? ")
    if choice in accounts:
        option1=1
    else:
        option1=0
    if choice2 in password:
        option2=1
    else:
        option2=0
    if option1==1 and option2==1:
        print "Welcome to Telemology,", choice
    else:
        print "The username or password you entered is incorrect. Please try again or register."

如您所见,它仅检查输入是否已在列表中。它不会查看输入是否具有相同的索引。我不能输入“accounts.index(choice)”,因为它将“choice”视为整数。由于字符串的缘故,引号也是如此。它不将它们视为变量。有什么办法解决这个问题吗?

我希望如果我的问题得到解答,两个人不会同时注册并导致索引出现故障。

I am trying to create a program in which you can create, log in, and delete accounts. I have made 2 lists, one with usernames and one with passwords. The script asks for an input and if you say log in, it says:

if loginchoice=='login':
    choice = raw_input("What is your username? ")
    choice2 = raw_input("What is your password? ")
    if choice in accounts:
        option1=1
    else:
        option1=0
    if choice2 in password:
        option2=1
    else:
        option2=0
    if option1==1 and option2==1:
        print "Welcome to Telemology,", choice
    else:
        print "The username or password you entered is incorrect. Please try again or register."

As you can see, it only checks to see if the inputs are already in the lists. It doesn't see if the inputs have the same index. I can't put "accounts.index(choice)" because it treats 'choice' as an integer. The same goes for quotations because of strings. It doesn't treat them as variables. Is there any way around this?

I hope that if my question gets answered, two people won't register simultaneously and glitch the indices.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

无尽的现实 2024-10-15 22:53:58

你想要的是一个映射,或者一本字典。它的密钥是用户名,其内容是该用户名的密码。

users = {} # this is the mapping
users["joe"] = "123" # it currently contains username "joe" with password "123"
...
username = raw_input("What is your username? ")
password = raw_input("What is your password? ")
if username in users.keys():
  expected_password = users[username]
  if expected_password == password:
    print "Welcome to Telemology,", username
  else:
    print "Didn't you forget your password,", username
else:
  print "Unknown user"

当然,在真实的系统中,您会存储加盐和加密的密码。

What you want is a mapping, or a dictionary. Its key would be username, its contents the password for that username.

users = {} # this is the mapping
users["joe"] = "123" # it currently contains username "joe" with password "123"
...
username = raw_input("What is your username? ")
password = raw_input("What is your password? ")
if username in users.keys():
  expected_password = users[username]
  if expected_password == password:
    print "Welcome to Telemology,", username
  else:
    print "Didn't you forget your password,", username
else:
  print "Unknown user"

Of course, in a real system you'd store passwords salted and encrypted.

陌上青苔 2024-10-15 22:53:58

您应该使用 getpass 模块来确保密码不会回显到屏幕上,并使用 hashlib 模块来确保不存储原始密码。这是一个使用两个模块的类,并且应该适用于 python2 和 python3。如果您想从文件中加载它,您应该将 UserDB.users 属性存储在文件中,您可以使用 json 模块来执行此操作。

import getpass
import hashlib
import random
import sys
class UserDB():
    def __init__(self, users=dict(), unprompt='Username:', pwprompt='Password:'):
        self.users=dict(users)
        self.unprompt=unprompt
        self.pwprompt=pwprompt
    def adduser(self):
        if sys.version_info.major==3:
            name=input(self.unprompt)
        elif sys.version_info.major==2:
            name=raw_input(self.unprompt)
        passwd=getpass.getpass(self.pwprompt).encode('utf-8')
        salt=bytes(random.randint(30, 95) for i in range(10))
        passwd=hashlib.pbkdf2_hmac('sha512', passwd, salt, 10*10)
        self.users[name]=[salt, passwd]
    def deluser(self, name):
        del self.users[name]
    def __str__(self):
        return str(self.users)
    def __repr__(self):
        return 'UserDB(users=%s, unprompt=%s, pwprompt=%s)' % (self.users,
                                                           ascii(self.unprompt),
                                                           ascii(self.pwprompt))
    def login(self):
        if sys.version_info.major==3:
            name=input(self.unprompt)
        elif sys.version_info.major==2:
            name=raw_input(self.unprompt)
        if name not in self.users:
            return False
        passwd=getpass.getpass(self.pwprompt).encode('utf-8')
        salt=self.users[name][0]
        passwd=hashlib.pbkdf2_hmac('sha512', passwd, salt, 10*10)
        return self.users[name][1]==passwd

You should use the getpass module to ensure that the password is not echoed to the screen and the hashlib module to mean that the raw password isn't stored. Here is a class which uses both modules and should work on python2 and python3. If you want to load it out of a file the you should store the UserDB.users attribute in a file, you could use the json module to do that.

import getpass
import hashlib
import random
import sys
class UserDB():
    def __init__(self, users=dict(), unprompt='Username:', pwprompt='Password:'):
        self.users=dict(users)
        self.unprompt=unprompt
        self.pwprompt=pwprompt
    def adduser(self):
        if sys.version_info.major==3:
            name=input(self.unprompt)
        elif sys.version_info.major==2:
            name=raw_input(self.unprompt)
        passwd=getpass.getpass(self.pwprompt).encode('utf-8')
        salt=bytes(random.randint(30, 95) for i in range(10))
        passwd=hashlib.pbkdf2_hmac('sha512', passwd, salt, 10*10)
        self.users[name]=[salt, passwd]
    def deluser(self, name):
        del self.users[name]
    def __str__(self):
        return str(self.users)
    def __repr__(self):
        return 'UserDB(users=%s, unprompt=%s, pwprompt=%s)' % (self.users,
                                                           ascii(self.unprompt),
                                                           ascii(self.pwprompt))
    def login(self):
        if sys.version_info.major==3:
            name=input(self.unprompt)
        elif sys.version_info.major==2:
            name=raw_input(self.unprompt)
        if name not in self.users:
            return False
        passwd=getpass.getpass(self.pwprompt).encode('utf-8')
        salt=self.users[name][0]
        passwd=hashlib.pbkdf2_hmac('sha512', passwd, salt, 10*10)
        return self.users[name][1]==passwd
开始看清了 2024-10-15 22:53:58

相反,创建一个用户列表,并创建 User 对象,该对象将用户名和密码作为属性。

拥有两个列表迟早会失去同步。

Create one list of users instead, and create User objects, which have username and password as attributes.

Having two lists is going to get desynchronized sooner or later.

相思碎 2024-10-15 22:53:58

既然是login,它应该是唯一的,你可以做一个字典:

users = {'username':'password', ...}

然后像这样检查:

choice = raw_input("What is your username? ")
choice2 = raw_input("What is your password? ")
if (choice in users) and (choice2 == users[choice]):
   # valid user
else:
   # login or password incorrect.

Since it is login, it should be unique, and you can make a dictionary:

users = {'username':'password', ...}

and then check like this:

choice = raw_input("What is your username? ")
choice2 = raw_input("What is your password? ")
if (choice in users) and (choice2 == users[choice]):
   # valid user
else:
   # login or password incorrect.
2024-10-15 22:53:58

我看到的一些问题:

  1. 您正在显示用户输入的密码。
  2. 您将接受任何用户名和密码,这意味着我可以使用密码登录任何帐户。
  3. 切勿存储明文密码。

我还没有找到不回显密码的便携式方法。 #2是用字典解决的。至于#3,您可能需要使用 hashlib 模块:

from hashlib import sha224

PASSWORD_HASHES = {}

def set_password(account, raw_password):
    PASSWORD_HASHES[account] = sha224(raw_password).digest()

def authenticate(account, raw_password):
    if account not in PASSWORD_HASHES:
        return False
    return PASSWORD_HASHES[account] == sha224(raw_password).digest()

替换 sha224 使用您想要的任何哈希算法;我还没有记录哪些仍然适合作为密码。

编辑:关于问题#1,如果您正在运行基于 POSIX 的系统(即不在 Windows 提示符下),您可以使用 Python 页面中的一些示例代码来实现 termios 模块获取密码而不将其回显到屏幕:

def getpass(prompt="Password: "):
    import termios, sys
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ECHO          # lflags
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
        passwd = raw_input(prompt)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
    return passwd

这不会放置 * 为角色准备;它只是抑制输入。要放置 *,您必须一次处理一个字符的输入并编写更多代码。

Some problems I'm seeing:

  1. You're displaying the password that the user types.
  2. You'll accept any username and any password, meaning I could log in to any account with my password.
  3. Never store a cleartext password.

I haven't found the portable way to not echo passwords. #2 is solved with a dictionary. As for #3, you'll probably want to use the hashlib module:

from hashlib import sha224

PASSWORD_HASHES = {}

def set_password(account, raw_password):
    PASSWORD_HASHES[account] = sha224(raw_password).digest()

def authenticate(account, raw_password):
    if account not in PASSWORD_HASHES:
        return False
    return PASSWORD_HASHES[account] == sha224(raw_password).digest()

Replace sha224 with whatever hash algorithm you want; I haven't kept track of which ones are still good for passwords.

EDIT: Regarding problem #1, if you're running a POSIX-based system (i.e. not at a Windows prompt), you can use some example code from Python's page for the termios module to get a password without echoing it to the screen:

def getpass(prompt="Password: "):
    import termios, sys
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ECHO          # lflags
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
        passwd = raw_input(prompt)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
    return passwd

This doesn't put *'s up for the characters; it just suppresses input. To put up *'s, you have to handle input one character at a time and write more code.

浪荡不羁 2024-10-15 22:53:58

我有一个非常简单的代码,允许对您的密码进行两次尝试,如果它们不匹配,它将无法工作

    users = {}
users["bob"] = "bob" 

username = raw_input("What is your username? ")
password = raw_input("What is your password? ")
if username in users.keys():
  expected_password = users[username]
  if expected_password == password:
    print "Welcome to Telemology,", username
  else:
    print "Didn't you forget your password,", username

password = raw_input("What is your password? ")
if username in users.keys():
  expected_password = users["bob"]
  if expected_password == password:
    print "Welcome to Telemology,", username
    #*here
  else:
    print "Didn't you forget your password,", username
else:
  print "Unknown user"
#continue your code for wrong here else*

i have a very simple code that alows two atemps at your password if they dont match it wont work

    users = {}
users["bob"] = "bob" 

username = raw_input("What is your username? ")
password = raw_input("What is your password? ")
if username in users.keys():
  expected_password = users[username]
  if expected_password == password:
    print "Welcome to Telemology,", username
  else:
    print "Didn't you forget your password,", username

password = raw_input("What is your password? ")
if username in users.keys():
  expected_password = users["bob"]
  if expected_password == password:
    print "Welcome to Telemology,", username
    #*here
  else:
    print "Didn't you forget your password,", username
else:
  print "Unknown user"
#continue your code for wrong here else*
软糖 2024-10-15 22:53:58

或者你可以只使用 SQLite3 db。这将允许您在运行时添加用户和密码。 SQLite3 本身也提供散列。

Or you could just SQLite3 db. That will allow you to add users and password on runtime. SQLite3 also provides hashing itself.

失而复得 2024-10-15 22:53:58

您始终可以使用帐户名及其各自的密码创建字典。
dictionary={'用户名':'密码','其他用户名':'其他密码'}
如果字典[选择] == 选择2:
print '欢迎来到 Telemology,%s' %choice

You can always create a dictionary with the account names and their respective passwords.
dictionary={'username':'password','some other username':'some other password'}
if dictionary[choice] == choice2:
print 'Welcome to Telemology, %s' %choice

不寐倦长更 2024-10-15 22:53:58

您应该将密码的输入更改为整数,如下所示:

password = raw_input("What is your password? ") --->this is your code
password = int(input("what is your password?")) --->modified code

然后一切都应该正常。

You should change the input to your password to integer as follows:

password = raw_input("What is your password? ") --->this is your code
password = int(input("what is your password?")) --->modified code

and then everything should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文