Tôi đang viết một chương trình cần người dùng đăng ký và đăng nhập bằng tài khoản. Tôi nhận được chương trình để người dùng tạo tên người dùng và mật khẩu của họ được lưu trong tệp văn bản bên ngoài [accountFile.txt], nhưng khi nói đến đăng nhập, tôi không biết làm thế nào để kiểm tra xem người dùng có nhập gì có mặt trong tệp văn bản.
Đây là những gì mã của tôi trông như thế nào:
def main[]:
register[]
def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.close[]
login[]
def login[]:
check = open["accountfile.txt","r"]
username = input["Please enter your username"]
password = input["Please enter your password"]
Tôi không biết phải làm gì từ thời điểm này.
Ngoài ra, đây là những gì một tài khoản đã đăng ký sẽ trông như thế nào trong tệp văn bản:
Ha2001 examplepassword
Sumner Evans
8.7335 huy hiệu vàng29 Huy hiệu bạc46 Huy hiệu đồng5 gold badges29 silver badges46 bronze badges
Hỏi ngày 13 tháng 10 năm 2017 lúc 22:43Oct 13, 2017 at 22:43
5
Sau khi mở tệp, bạn có thể sử dụng
def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
5 để đọc văn bản vào danh sách các cặp tên người dùng/mật khẩu. Vì bạn đã tách tên người dùng và mật khẩu với một khoảng trống, mỗi cặp là chuỗi trông giống như def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
6, mà bạn có thể chia thành một danh sách hai chuỗi với def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
7. Từ đó, kiểm tra xem tên người dùng và mật khẩu có phù hợp với đầu vào của người dùng hay không. Nếu bạn muốn nhiều người dùng khi tệp TXT của bạn phát triển, bạn cần thêm một dòng mới sau mỗi cặp tên người dùng/mật khẩu.def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
Đã trả lời ngày 13 tháng 10 năm 2017 lúc 22:50Oct 13, 2017 at 22:50
Brenden Petersenbrenden PetersenBrenden Petersen
1.9531 huy hiệu vàng9 Huy hiệu bạc1 gold badge9 silver badges10 bronze badges
2
filename = r"c:/userfile.txt"
with open[filename,"rt"] as f
text = f.readline[]
username, password = text.strip[].split[]
Chương trình này giả định những điều sau đây
Bạn chỉ đọc dòng đầu tiên của tệp
Dòng đầu tiên của tệp chứa tên người dùng và mật khẩu
Dòng đơn giản là
8 không có ký tự khác.def register[]: username = input["Please input the first 2 letters of your first name and your birth year "] password = input["Please input your desired password "] file = open["accountfile.txt","a"] file.write[username] file.write[" "] file.write[password] file.write["\n"] file.close[] if login[]: print["You are now logged in..."] else: print["You aren't logged in!"] def login[]: username = input["Please enter your username"] password = input["Please enter your password"] for line in open["accountfile.txt","r"].readlines[]: # Read the lines login_info = line.split[] # Split on the space, and store the results in a list of two strings if username == login_info[0] and password == login_info[1]: print["Correct credentials!"] return True print["Incorrect credentials."] return False
Tôi thích đóng góp cho nguồn mở, nhưng tôi muốn giữ mật khẩu của mình cho riêng mình! Python là một ngôn ngữ keo tuyệt vời để tự động hóa các tác vụ và gần đây tôi đã sử dụng nó để đăng nhập vào máy chủ web của mình bằng SFTP và tự động hóa phân tích nhật ký, quản lý tệp và cập nhật phần mềm. Các tập lệnh Python tôi đang làm việc cần biết thông tin đăng nhập của mình, nhưng tôi muốn cam kết chúng kiểm soát nguồn và chia sẻ chúng trên GitHub để tôi phải cẩn thận sử dụng một chiến lược nhằm giảm thiểu rủi ro vô tình rò rỉ các bí mật này lên Internet . Python is a great glue language for automating tasks, and recently I've been using it to log in to my web server using SFTP and automate log analysis, file management, and software updates. The Python scripts I'm working on need to know my login information, but I want to commit them to source control and share them on GitHub so I have to be careful to use a strategy which minimizes risk of inadvertently leaking these secrets onto the internet.
Bài đăng này khám phá các tùy chọn khác nhau để quản lý thông tin đăng nhập trong các tập lệnh Python trong kho công cộng. Có nhiều cách khác nhau để quản lý thông tin đăng nhập với Python, và tôi đã rất ngạc nhiên khi biết về một số cách mới khi tôi đang nghiên cứu chủ đề này. Bài đăng này xem xét các tùy chọn phổ biến nhất, bắt đầu với sự không an toàn nhất và làm việc theo cách của nó theo các phương pháp được đánh giá cao nhất để quản lý bí mật. There are many different ways to manage credentials with Python, and I was surprised to learn of some new ones as I was researching this topic. This post reviews the most common options, starting with the most insecure and working its way up to the most highly regarded methods for managing secrets.
Mật khẩu văn bản đơn giản trong mã
Nguy hiểm: Không bao giờ làm điều này Never do this
Bạn có thể đặt một mật khẩu hoặc khóa API trực tiếp trong tập lệnh Python của mình, nhưng ngay cả khi bạn có ý định xóa nó sau này, luôn có cơ hội bạn sẽ vô tình cam kết kiểm soát nguồn mà không nhận ra, gây rủi ro bảo mật mãi mãi. Phương pháp này là phải tránh bằng mọi giá!
username = "myUsername"
password = "S3CR3T_P455W0RD"
logIn[username, password]
Mật khẩu bị che khuất trong mã
Nguy hiểm: Không bao giờ làm điều này Never do this
Bạn có thể đặt một mật khẩu hoặc khóa API trực tiếp trong tập lệnh Python của mình, nhưng ngay cả khi bạn có ý định xóa nó sau này, luôn có cơ hội bạn sẽ vô tình cam kết kiểm soát nguồn mà không nhận ra, gây rủi ro bảo mật mãi mãi. Phương pháp này là phải tránh bằng mọi giá!
"""Demonstrate conversion to/from base 64"""
import base64
def obfuscate[plainText]:
plainBytes = plainText.encode['ascii']
encodedBytes = base64.b64encode[plainBytes]
encodedText = encodedBytes.decode['ascii']
return encodedText
def deobfuscate[obfuscatedText]:
obfuscatedBytes = obfuscatedText.encode['ascii']
decodedBytes = base64.b64decode[obfuscatedBytes]
decodedText = decodedBytes.decode['ascii']
return decodedText
original = "S3CR3T_P455W0RD"
obfuscated = obfuscate[original]
deobfuscated = deobfuscate[obfuscated]
print["original: " + original]
print["obfuscated: " + obfuscated]
print["deobfuscated: " + deobfuscated]
original: S3CR3T_P455W0RD
obfuscated: UzNDUjNUX1A0NTVXMFJE
deobfuscated: S3CR3T_P455W0RD
Mật khẩu bị che khuất trong mã
Một ý tưởng ít khủng khiếp hơn là làm xáo trộn mật khẩu văn bản đơn giản bằng cách lưu trữ chúng dưới dạng chuỗi 64 cơ sở. Bạn sẽ không biết mật khẩu chỉ bằng cách nhìn thấy nó, nhưng bất kỳ ai có chuỗi đều có thể dễ dàng giải mã nó. Các trang web như //www.base644decode.org rất hữu ích cho việc này. This method is prone to mistakes. Ensure the text file is never committed to source control.
Mật khẩu trong các tệp văn bản đơn giản
with open["secrets.txt"] as f:
lines = f.readlines[]
username = lines[0].strip[]
password = lines[1].strip[]
print[f"USERNAME={username}, PASSWORD={password}"]
Cảnh báo: Phương pháp này dễ bị lỗi. Đảm bảo tệp văn bản không bao giờ được cam kết kiểm soát nguồn.
Bạn có thể lưu trữ tên người dùng/mật khẩu trên hai dòng đầu tiên của tệp văn bản đơn giản, sau đó sử dụng Python để đọc nó khi bạn cần.
Nếu tệp văn bản nằm trong thư mục kho lưu trữ, bạn nên sửa đổi def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
9 để đảm bảo nó không được theo dõi bởi điều khiển nguồn. Có một rủi ro là bạn có thể quên làm điều này, để lộ thông tin đăng nhập của bạn trực tuyến! Một ý tưởng tốt hơn có thể là đặt tệp bí mật bên ngoài thư mục kho lưu trữ của bạn hoàn toàn.
def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
Có những thư viện làm cho điều này dễ dàng hơn. Một ví dụ là Python Decouple thực hiện rất nhiều logic này một cách duyên dáng và thậm chí có thể kết hợp các cài đặt từ nhiều tệp [ví dụ: các tệp
0 so vớifilename = r"c:/userfile.txt" with open[filename,"rt"] as f text = f.readline[] username, password = text.strip[].split[]
1] cho các môi trường có thể hưởng lợi từ các tùy chọn cấu hình nâng cao hơn. Xem các ghi chú bên dưới về các thư viện trợ giúp mà các biến môi trường và các tệpfilename = r"c:/userfile.txt" with open[filename,"rt"] as f text = f.readline[] username, password = text.strip[].split[]
1 This method is prone to mistakes. Ensure the secrets module is never committed to source control.filename = r"c:/userfile.txt" with open[filename,"rt"] as f text = f.readline[] username, password = text.strip[].split[]
Mật khẩu trong các mô -đun Python
Cảnh báo: Phương pháp này dễ bị lỗi. Đảm bảo mô -đun bí mật không bao giờ được cam kết kiểm soát nguồn.Tương tự như một tệp văn bản thuần túy không được theo dõi bởi điều khiển nguồn [lý tưởng bên ngoài thư mục kho lưu trữ hoàn toàn], bạn có thể lưu trữ mật khẩu dưới dạng các biến trong mô -đun Python sau đó nhập nó.
Ha2001 examplepassword
0from mySecrets import username, password
print[f"USERNAME={username}, PASSWORD={password}"]
Nếu tệp bí mật của bạn nằm trong một thư mục tối nghĩa, bạn sẽ phải thêm nó vào đường dẫn của mình để mô -đun có thể được tìm thấy khi nhập.
Đừng đặt tên cho mô -đun của bạn
3 vì mô -đun Bí mật là một phần của thư viện tiêu chuẩn và có thể sẽ được nhập vào thay thế. This method may store plain text passwords in your command history.filename = r"c:/userfile.txt" with open[filename,"rt"] as f text = f.readline[] username, password = text.strip[].split[]
Mật khẩu như đối số chương trình
Đây không phải là một ý tưởng tuyệt vời vì mật khẩu được nhìn thấy trong văn bản đơn giản trong bảng điều khiển và cũng có thể được lưu trữ trong lịch sử lệnh. Tuy nhiên, bạn không có khả năng vô tình cam kết mật khẩu để kiểm soát nguồn.
Ha2001 examplepassword
1Ha2001 examplepassword
2Ha2001 examplepassword
3Nhập mật khẩu vào bảng điều khiển
Ha2001 examplepassword
4Bạn có thể yêu cầu người dùng nhập mật khẩu của họ vào bảng điều khiển, nhưng các ký tự sẽ được hiển thị khi chúng được nhập.
Python có một mô -đun GetPass trong thư viện tiêu chuẩn được thực hiện để nhắc người dùng về mật khẩu làm đầu vào bảng điều khiển. Không giống như
filename = r"c:/userfile.txt"
with open[filename,"rt"] as f
text = f.readline[]
username, password = text.strip[].split[]
4, các ký tự không hiển thị vì mật khẩu được gõ.Ha2001 examplepassword
5Đây là một phương pháp thú vị. Nó nhanh và đơn giản, nhưng hơi kỳ quặc. Các nhược điểm là [1] nó yêu cầu mật khẩu phải ở trong bảng tạm có thể đưa nó đến các chương trình khác, [2] nó yêu cầu cài đặt thư viện không đạt tiêu chuẩn và [3] nó sẽ không dễ dàng hoạt động trong môi trường máy chủ.
Ha2001 examplepassword
6Lưu ý rằng tôi tin tưởng pyperclip nhiều hơn clipboard [đó chỉ là một nhà phát triển khác kết thúc pyperclip]
Chạy sau khi sao chép mật khẩu vào bảng tạm:
Yêu cầu thông tin đăng nhập với TK
Ha2001 examplepassword
7Ha2001 examplepassword
8Thư viện đồ họa TK là một bộ công cụ tiện ích đồ họa đa nền tảng đi kèm với Python. Một cửa sổ đăng nhập thu thập tên người dùng và mật khẩu có thể được tạo theo chương trình và được gói trong một hàm để dễ dàng đưa vào các tập lệnh mà không có GUI.
Tôi thấy kỹ thuật này đặc biệt hữu ích khi tên người dùng và mật khẩu được lưu trữ trong trình quản lý mật khẩu.
Quản lý mật khẩu với Keyring
Ha2001 examplepassword
9def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
0def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
1Gói Keyring cung cấp một cách dễ dàng để truy cập dịch vụ Keyring của hệ thống từ Python. Trên MacOS, nó sử dụng Keychain, trên Windows, nó sử dụng khóa thông tin Windows và trên Linux, nó có thể sử dụng dịch vụ bí mật của Kwallet hoặc Gnome của KDE.
Nhược điểm của Keyrings là [1] nó yêu cầu một thư viện không đạt tiêu chuẩn, [2] triển khai có thể là đặc trưng của OS, [3] nó có thể không dễ dàng hoạt động trong môi trường đám mây.
Hãy chắc chắn khởi động lại phiên giao diện điều khiển của bạn sau khi chỉnh sửa các biến môi trường trước khi thử đọc chúng từ bên trong Python.
def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
2Có nhiều thư viện trợ giúp như Python-Dotenv và Python Decouple có thể sử dụng các tệp
filename = r"c:/userfile.txt"
with open[filename,"rt"] as f
text = f.readline[]
username, password = text.strip[].split[]
1 cục bộ để đặt các biến môi trường động khi chương trình của bạn chạy. Như đã lưu ý trong các phần trước, khi lưu trữ mật khẩu theo văn bản đơn giản trong cấu trúc tệp của kho lưu trữ của bạn, hãy cực kỳ cẩn thận khi không cam kết các tệp này để kiểm soát nguồn!Ví dụ
filename = r"c:/userfile.txt"
with open[filename,"rt"] as f
text = f.readline[]
username, password = text.strip[].split[]
1 Tệp:def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
3Gói
filename = r"c:/userfile.txt"
with open[filename,"rt"] as f
text = f.readline[]
username, password = text.strip[].split[]
7 có thể tải các biến filename = r"c:/userfile.txt"
with open[filename,"rt"] as f
text = f.readline[]
username, password = text.strip[].split[]
1 dưới dạng biến môi trường khi tập lệnh Python chạy:def register[]:
username = input["Please input the first 2 letters of your first name and your birth year "]
password = input["Please input your desired password "]
file = open["accountfile.txt","a"]
file.write[username]
file.write[" "]
file.write[password]
file.write["\n"]
file.close[]
if login[]:
print["You are now logged in..."]
else:
print["You aren't logged in!"]
def login[]:
username = input["Please enter your username"]
password = input["Please enter your password"]
for line in open["accountfile.txt","r"].readlines[]: # Read the lines
login_info = line.split[] # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print["Correct credentials!"]
return True
print["Incorrect credentials."]
return False
4Tài nguyên bổ sung
- Sử dụng các tệp .ENV cho các biến môi trường trong các ứng dụng Python
- Biến môi trường so với bí mật trong Python
- Cách đặt các biến môi trường
- Làm việc với các biến môi trường trong Python
- Cách đặt và nhận các biến môi trường trong Python
- Python-DOTENV đọc các cặp giá trị khóa từ tệp .ENV và có thể đặt chúng thành các biến môi trường. Nó giúp phát triển các ứng dụng theo các nguyên tắc 12 yếu tố.
- Python Decouple giúp bạn sắp xếp các cài đặt của mình để bạn có thể thay đổi tham số mà không phải triển khai lại ứng dụng của mình.
Làm thế nào để bạn quản lý thông tin đăng nhập trong Python? Nếu bạn muốn chia sẻ phản hồi hoặc phương pháp sáng tạo mà bạn sử dụng mà tôi chưa thảo luận ở trên, hãy gửi email cho tôi và tôi có thể đưa các đề xuất của bạn vào tài liệu này.