Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

getpass() และ getuser() ใน Python (ป้อนรหัสผ่านโดยไม่แสดงบนหน้าจอ)

เมื่อเขียนโปรแกรม Python ที่ต้องการการป้อนรหัสผ่านก่อนรัน สามารถใช้โมดูล getpass และ getuser ซึ่งมีฟังก์ชันสำหรับจัดการรหัสผ่านและดึงชื่อผู้ใช้

การใช้งานพร้อม Prompt

ฟังก์ชัน getpass.getpass() จะแสดง prompt แล้วรอรับค่าจนกว่าจะกด Enter

โค้ดตัวอย่าง (บันทึกเป็น logon.py)

import getpass
try:
    pwd = getpass.getpass()
except Exception as err:
    print('Error Occurred:', err)
else:
    print('Password entered:', pwd)

ผลลัพธ์

$ python logon.py
Password: 
Password entered: abracadbra

ใช้กับคำถามความปลอดภัย (Security Question)

สามารถกำหนด prompt เป็นคำถามช่วยจำรหัสผ่านได้

โค้ดตัวอย่าง

import getpass
pwd = getpass.getpass(prompt='What is your favorite colour? ')
if pwd == 'Crimson':
    print('You are in!')
else:
    print('Try Again')

ผลลัพธ์

$ python logon.py
What is your favorite colour? 
You are in!

แสดงชื่อผู้ใช้ (Displaying Login Name)

ใช้ getpass.getuser() เพื่อดึงชื่อผู้ใช้ที่รันสคริปต์

โค้ดตัวอย่าง

import getpass
user = getpass.getuser()
while True:
    pwd = getpass.getpass("User Name: ", user)
    if pwd == 'Crimson':
        print("You are in!")
    else:
        print("The password you entered is wrong.")

ผลลัพธ์

User Name: user1
You are in!