Python登录脚本;用户名和密码在单独的文件中 [英] Python Login Script; Usernames and Passwords in a separate file
问题描述
我正在寻求帮助,以使我的Python脚本模仿登录功能,同时将凭据存储在单独的文件中.
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.
Python脚本如下:
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()
文本文件包含以下格式的用户名和密码:Test:TestPW Chris:ChrisPW Admin:AdminPW,每个凭据都位于新行上.
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
会告诉您用户名是否在凭据文件中(即,它是否是credentials
词典中的密钥)
will tell you if the username is in the credentials file (ie. if it's a key in the credentials
dictionary)
然后:
credentials[username] == password
这篇关于Python登录脚本;用户名和密码在单独的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!