Python Login Script; Usernames and Passwords in a separate file

人走茶凉 提交于 2019-12-17 20:42:55

问题


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.

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:

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.

As I said previously, any help is appreciated! Thanks.


回答1:


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 credentials dictionary)

And then:

credentials[username] == password



回答2:


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)()



回答3:


You should not use 2 loops. It would just tell the person that they guessed the username. Just saying. use one loop.

also check my repl.it it page for a better sso that can have like 100 people at once without else if statements

Here it is: https://repl.it/@AmazingPurplez/CatSSO

Has errors. Was developed only by me so +rep to me.

  • rep to: Joran Beasley

Could not post code here because of "indention errors" like frick it! but I will still try a simpler version

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



回答4:


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."


来源:https://stackoverflow.com/questions/21560739/python-login-script-usernames-and-passwords-in-a-separate-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!