Prompt for a password, with echo turned off. Args: prompt: Written on stream to ask for the input. Default: 'Password: ' stream: A writable file object to display the prompt. Defaults to the tty. If no tty is available defaults to sys.stderr. echo_char: A sing
(prompt='Password: ', stream=None, *, echo_char=None)
| 27 | |
| 28 | |
| 29 | def unix_getpass(prompt='Password: ', stream=None, *, echo_char=None): |
| 30 | """Prompt for a password, with echo turned off. |
| 31 | |
| 32 | Args: |
| 33 | prompt: Written on stream to ask for the input. Default: 'Password: ' |
| 34 | stream: A writable file object to display the prompt. Defaults to |
| 35 | the tty. If no tty is available defaults to sys.stderr. |
| 36 | echo_char: A single ASCII character to mask input (e.g., '*'). |
| 37 | If None, input is hidden. |
| 38 | Returns: |
| 39 | The seKr3t input. |
| 40 | Raises: |
| 41 | EOFError: If our input tty or stdin was closed. |
| 42 | GetPassWarning: When we were unable to turn echo off on the input. |
| 43 | |
| 44 | Always restores terminal settings before returning. |
| 45 | """ |
| 46 | _check_echo_char(echo_char) |
| 47 | |
| 48 | passwd = None |
| 49 | with contextlib.ExitStack() as stack: |
| 50 | try: |
| 51 | # Always try reading and writing directly on the tty first. |
| 52 | fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY) |
| 53 | tty = io.FileIO(fd, 'w+') |
| 54 | stack.enter_context(tty) |
| 55 | input = io.TextIOWrapper(tty) |
| 56 | stack.enter_context(input) |
| 57 | if not stream: |
| 58 | stream = input |
| 59 | except OSError: |
| 60 | # If that fails, see if stdin can be controlled. |
| 61 | stack.close() |
| 62 | try: |
| 63 | fd = sys.stdin.fileno() |
| 64 | except (AttributeError, ValueError): |
| 65 | fd = None |
| 66 | passwd = fallback_getpass(prompt, stream) |
| 67 | input = sys.stdin |
| 68 | if not stream: |
| 69 | stream = sys.stderr |
| 70 | |
| 71 | if fd is not None: |
| 72 | try: |
| 73 | old = termios.tcgetattr(fd) # a copy to save |
| 74 | new = old[:] |
| 75 | new[3] &= ~termios.ECHO # 3 == 'lflags' |
| 76 | if echo_char: |
| 77 | new[3] &= ~termios.ICANON |
| 78 | tcsetattr_flags = termios.TCSAFLUSH |
| 79 | if hasattr(termios, 'TCSASOFT'): |
| 80 | tcsetattr_flags |= termios.TCSASOFT |
| 81 | try: |
| 82 | termios.tcsetattr(fd, tcsetattr_flags, new) |
| 83 | passwd = _raw_input(prompt, stream, input=input, |
| 84 | echo_char=echo_char) |
| 85 | |
| 86 | finally: |
nothing calls this directly
no test coverage detected