ChatGPT解决这个技术问题 Extra ChatGPT

Getting a hidden password input

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.


S
Sven Marnach

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.


will work, but how can one be careful of a "hacker" that will make a copy of the script and then comment out the line that requires user password?
@asf107: If the hacker can edit the source code, there are other problems to worry about.
@asf107 - The idea behind requesting a password is so that you can pass it along to authenticate with something (IE, I'm using this to request a password to authenticate with an online server). If a hacker commented out the line, the program would simply fail because the server wouldn't be authenticated with anymore. The idea behind using 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.
C
Cœur
import getpass

pswd = getpass.getpass('Password:')

getpass works on Linux, Windows, and Mac.


"Password: " (with a space after the colon) is the default prompt, so there's often no need to specify it in the call to getpass.getpass().
getpass is a standard library module that's been around since at least Python 2.5
this gave me an error 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
getpass() Does not work with IDLE. Is there another way to achieve this without getpass()?
To have the prompt is on the stderr (you will also need import sys): getpass.getpass(<string>,sys.stderr)
R
RanRag

Use getpass for this purpose.

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


how about with echoing * chars?
w
wjandrea

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

this is windows only but at least it's not repeating the getpass answer. Good
wont handle backspaces.
I'm not sure whether your code is for Python 2.x, but this does not work for me. I'm running Python 3.x. First error I got was a TypeError for the 'passwor += x' line. It said: "can't convert bytes object to str implicitly". I changed the line so that I explicitly cast x to string such as: "password += str(x)". But the code still does not work. When I run it, it doesn't prompt me for input, it just prints the asterisk forever.
@Larper It is for Python 2, see the last line of the code
@MilkyWay90 Some modifications were required for this code to be compatible with Python 3. Have submitted a modified code edit. Hope it gets approved :)
M
Mostafa Hassan

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.


DON't DO THIS... people have already done it... stackoverflow.com/a/67327327/701532
S
Sagar

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

DON't DO THIS... people have already done it... stackoverflow.com/a/67327327/701532
@anthony I just found it wiser to write a 16 line function with standard imports. Also, I get to see what's running under the hood and I can customize things as required
Yes customise it for yourself... but what about other users? Also from personal experience, even handing stars can get complicated fast, dealing with control characters, unicode, kill lines, or even a simple... turning off echo (tab of backspace at start of input). The better why do it is to focus instead on the ability to use a 'password helper', like "system-ask-password" which already provides a 'star password input'. SSH and SUDO can both do this! The user can then select their own way of inputting passwords, be it with stars, or from a password manager, or some other source!