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.
解决方案
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