Getting command-line password input in Python

2018-12-31 22:14发布

问题:

You know how in Linux when you try some Sudo stuff it tells you to enter the password and, as you type, nothing is shown in the terminal window (the password is not shown)?

Is there a way to do that in Python? I\'m working on a script that requires so sensitive info and would like for it to be hidden when I\'m typing it.

In other words, I want to get the password from the user without showing the password.

回答1:

import getpass

pswd = getpass.getpass(\'Password:\')

This works on Linux, Windows, and Mac.



回答2:

Use getpass for this purpose.

getpass.getpass - Prompt the user for a password without echoing



回答3:

import sys
import msvcrt

passwor = \'\'
while True:
    x = msvcrt.getch()
    if x == \'\\r\':
        break
    sys.stdout.write(\'*\')
    passwor +=x

print \'\\n\'+passwor

this code will print astrix instead of every letter



回答4:

import getpass
p = str(\"null\")  # user\'s input start value
pas = str(\"password\")  # password value
while p != pas:
    p = getpass.getpass(\"Insert your password: \")  # password input
print(\"ay\")  # when you get the password, the output is \"ay\"


回答5:

Use this to re-ask for the password if inserted pass is not the world hello:

import getpass

password = getpass.getpass(\'Insert your password:\')

while password != \'hello\':
   print(\'... Sorry.. Wrong pass\')
   password = getpass.getpass(\'Insert your password again:\')