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.
Use getpass.getpass()
:
from getpass import getpass
password = getpass()
An optional prompt can be passed as parameter; the default is "Password: "
.
Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.
import getpass
pswd = getpass.getpass('Password:')
getpass works on Linux, Windows, and Mac.
Warning (from warnings module): File "C:\Python27\lib\getpass.py", line 92 return fallback_getpass(prompt, stream) GetPassWarning: Can not control echo on the terminal. Warning: Password input may be echoed.
in the IDLE, but worked well in the command prompt, found the reason here
import sys
): getpass.getpass(
<string>,sys.stderr)
Use getpass for this purpose.
getpass.getpass - Prompt the user for a password without echoing
This code will print an asterisk instead of every letter.
import sys
import msvcrt
passwor = ''
while True:
x = msvcrt.getch()
if x == '\r':
break
sys.stdout.write('*')
passwor +=x
print '\n'+passwor
getpass
answer. Good
Updating on the answer of @Ahmed ALaa
# import msvcrt
import getch
def getPass():
passwor = ''
while True:
x = getch.getch()
# x = msvcrt.getch().decode("utf-8")
if x == '\r' or x == '\n':
break
print('*', end='', flush=True)
passwor +=x
return passwor
print("\nout=", getPass())
msvcrt us only for windows, but getch from PyPI should work for both (I only tested with linux). You can also comment/uncomment the two lines to make it work for windows.
Here is my code based off the code offered by @Ahmed ALaa
Features:
Works for passwords up to 64 characters
Accepts backspace input
Outputs * character (DEC: 42 ; HEX: 0x2A) instead of the input character
Demerits:
Works on Windows only
The function secure_password_input()
returns the password as a string
when called. It accepts a Password Prompt string, which will be displayed to the user to type the password
def secure_password_input(prompt=''):
p_s = ''
proxy_string = [' '] * 64
while True:
sys.stdout.write('\x0D' + prompt + ''.join(proxy_string))
c = msvcrt.getch()
if c == b'\r':
break
elif c == b'\x08':
p_s = p_s[:-1]
proxy_string[len(p_s)] = " "
else:
proxy_string[len(p_s)] = "*"
p_s += c.decode()
sys.stdout.write('\n')
return p_s
Success story sharing
getpass()
is so that nobody can look at the source code and find out your password just by reading it, and nobody can get your password by just staring over your shoulder and reading your password off the screen when you type it in.