Getting command-line password input in Python

2018-12-31 22:17发布

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.

5条回答
人间绝色
2楼-- · 2018-12-31 22:23

Use getpass for this purpose.

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

查看更多
浮光初槿花落
3楼-- · 2018-12-31 22:26
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"
查看更多
低头抚发
4楼-- · 2018-12-31 22:31
import getpass

pswd = getpass.getpass('Password:')

This works on Linux, Windows, and Mac.

查看更多
大哥的爱人
5楼-- · 2018-12-31 22:32

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:')
查看更多
一个人的天荒地老
6楼-- · 2018-12-31 22:37
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

查看更多
登录 后发表回答