Python登录脚本;用户名和密码在一个单独的文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21560739/
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
Python Login Script; Usernames and Passwords in a separate file
提问by Chrisosaurus
I'm looking for assistance to get my Python script to imitate a log-in feature while the credentials are stored in a separate file.
我正在寻求帮助,让我的 Python 脚本模仿登录功能,同时将凭据存储在单独的文件中。
I got it to work from hard-coded Username and Password, and it also reads in a file, but I'm having some difficulty finding out how to link the two together.
我通过硬编码的用户名和密码让它工作,它也读入一个文件,但我很难找到如何将两者链接在一起。
Any assistance is appreciated.
任何帮助表示赞赏。
The Python script is as follows:
Python脚本如下:
print "Login Script"
import getpass
CorrectUsername = "Test"
CorrectPassword = "TestPW" 
loop = 'true'
while (loop == 'true'):
    username = raw_input("Please enter your username: ")
    if (username == CorrectUsername):
        loop1 = 'true'
        while (loop1 == 'true'):
            password = getpass.getpass("Please enter your password: ")
            if (password == CorrectPassword):
                print "Logged in successfully as " + username
                loop = 'false'
                loop1 = 'false'
            else:
                print "Password incorrect!"
    else:
        print "Username incorrect!"
I found this somewhere else that helped me read the file in, and it does print the contents of the text file, but I am unsure on how to progress from this:
我在其他地方找到了这个帮助我读入文件的东西,它确实打印了文本文件的内容,但我不确定如何从这里取得进展:
with open('Usernames.txt', 'r') as f:
    data = f.readlines()
    #print data
for line in data:
    words = line.split() 
The text file contains the Usernames and Passwords in a format of: Test:TestPW Chris:ChrisPW Admin:AdminPW with each credential on a new line.
该文本文件包含用户名和密码,格式为:Test:TestPW Chris:ChrisPW Admin:AdminPW,每个凭据都在一个新行上。
As I said previously, any help is appreciated! Thanks.
正如我之前所说,任何帮助表示赞赏!谢谢。
采纳答案by Ricardo Cárdenes
You could start having a dictionary of usernames and passwords:
你可以开始拥有一个用户名和密码字典:
credentials = {}
with open('Usernames.txt', 'r') as f:
    for line in f:
        user, pwd = line.strip().split(':')
        credentials[user] = pwd
Then you have two easy tests:
然后你有两个简单的测试:
username in credentials
will tell you if the username is in the credentials file (ie. if it's a key in the credentialsdictionary)
会告诉你用户名是否在凭证文件中(即如果它是credentials字典中的一个键)
And then:
进而:
credentials[username] == password
回答by Joran Beasley
import hashlib ,os
resource_file = "passwords.txt"
def encode(username,password):
    return "$%s::%s$"%(username,hashlib.sha1(password).hexdigest())
def add_user(username,password):
    if os.path.exists(resource_file):
        with open(resource_file) as f:
            if "$%s::"%username in f.read():
                raise Exception("user already exists")
    with open(resource_file,"w") as f:
         print >> f, encode(username,password)
    return username
def check_login(username,password):
    with open(resource_file) as f:
        if encode(username,password) in f.read():
           return username
def create_username():
     try: 
         username = add_user(raw_input("enter username:"),raw_input("enter password:"))
         print "Added User! %s"%username
     except Exception as e:
         print "Failed to add user %s! ... user already exists??"%username
def login():
     if check_login(raw_input("enter username:"),raw_input("enter password:")):
        print "Login Success!!"
     else:
        print "there was a problem logging in"
while True:
    {'c':create_username,'l':login}.get(raw_input("(c)reate user\n(l)ogin\n------------\n>").lower(),login)()
回答by CodeDat
username = raw_input("Username:")
password = raw_input("Password:")
if password == "CHANGE" and username == "CHANGE":
    print "Logged in as CHANGE"
else:
    print "Incorrect Password. Please try again."
回答by CodeDat
You should not use 2 loops. It would just tell the person that they guessed the username. Just saying. use one loop.
您不应该使用 2 个循环。它只会告诉人们他们猜到了用户名。就是说。使用一个循环。
also check my repl.it it page for a better sso that can have like 100 people at once without else if statements
还要检查我的 repl.it it 页面以获得更好的 sso,它可以同时容纳 100 人,而没有 else if 语句
Here it is: https://repl.it/@AmazingPurplez/CatSSO
这是:https: //repl.it/@AmazingPurplez/CatSSO
Has errors. Was developed only by me so +rep to me.
有错误。仅由我开发,所以 +rep 给我。
- rep to: Joran Beasley
 
- 代表:乔兰·比斯利
 
Could not post code here because of "indention errors" like frick it! but I will still try a simpler version
由于“缩进错误”而无法在此处发布代码,例如 frick it!但我还是会尝试更简单的版本
import getpass
username = "username"
password = "password"
loop = True
while loop == True:
    userinput = input("question")
    passinput = getpass.getpass("question")
    if userinput == username and passinput == password:
        statements
        break
    else:
        statements

