1"""Utilities to get a password and/or the current user name. 2 3getpass(prompt[, stream]) - Prompt for a password, with echo turned off. 4getuser() - Get the user name from the environment or password database. 5 6GetPassWarning - This UserWarning is issued when getpass() cannot prevent 7 echoing of the password contents while reading. 8 9On Windows, the msvcrt module will be used. 10 11""" 12 13# Authors: Piers Lauder (original) 14# Guido van Rossum (Windows support and cleanup) 15# Gregory P. Smith (tty support & GetPassWarning) 16 17import contextlib 18import io 19import os 20import sys 21 22__all__ = ["getpass","getuser","GetPassWarning"] 23 24 25class GetPassWarning(UserWarning): pass 26 27 28def unix_getpass(prompt='Password: ', stream=None): 29 """Prompt for a password, with echo turned off. 30 31 Args: 32 prompt: Written on stream to ask for the input. Default: 'Password: ' 33 stream: A writable file object to display the prompt. Defaults to 34 the tty. If no tty is available defaults to sys.stderr. 35 Returns: 36 The seKr3t input. 37 Raises: 38 EOFError: If our input tty or stdin was closed. 39 GetPassWarning: When we were unable to turn echo off on the input. 40 41 Always restores terminal settings before returning. 42 """ 43 passwd = None 44 with contextlib.ExitStack() as stack: 45 try: 46 # Always try reading and writing directly on the tty first. 47 fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY) 48 tty = io.FileIO(fd, 'w+') 49 stack.enter_context(tty) 50 input = io.TextIOWrapper(tty) 51 stack.enter_context(input) 52 if not stream: 53 stream = input 54 except OSError: 55 # If that fails, see if stdin can be controlled. 56 stack.close() 57 try: 58 fd = sys.stdin.fileno() 59 except (AttributeError, ValueError): 60 fd = None 61 passwd = fallback_getpass(prompt, stream) 62 input = sys.stdin 63 if not stream: 64 stream = sys.stderr 65 66 if fd is not None: 67 try: 68 old = termios.tcgetattr(fd) # a copy to save 69 new = old[:] 70 new[3] &= ~termios.ECHO # 3 == 'lflags' 71 tcsetattr_flags = termios.TCSAFLUSH 72 if hasattr(termios, 'TCSASOFT'): 73 tcsetattr_flags |= termios.TCSASOFT 74 try: 75 termios.tcsetattr(fd, tcsetattr_flags, new) 76 passwd = _raw_input(prompt, stream, input=input) 77 finally: 78 termios.tcsetattr(fd, tcsetattr_flags, old) 79 stream.flush() # issue7208 80 except termios.error: 81 if passwd is not None: 82 # _raw_input succeeded. The final tcsetattr failed. Reraise 83 # instead of leaving the terminal in an unknown state. 84 raise 85 # We can't control the tty or stdin. Give up and use normal IO. 86 # fallback_getpass() raises an appropriate warning. 87 if stream is not input: 88 # clean up unused file objects before blocking 89 stack.close() 90 passwd = fallback_getpass(prompt, stream) 91 92 stream.write('\n') 93 return passwd 94 95 96def win_getpass(prompt='Password: ', stream=None): 97 """Prompt for password with echo off, using Windows getwch().""" 98 if sys.stdin is not sys.__stdin__: 99 return fallback_getpass(prompt, stream) 100 101 for c in prompt: 102 msvcrt.putwch(c) 103 pw = "" 104 while 1: 105 c = msvcrt.getwch() 106 if c == '\r' or c == '\n': 107 break 108 if c == '\003': 109 raise KeyboardInterrupt 110 if c == '\b': 111 pw = pw[:-1] 112 else: 113 pw = pw + c 114 msvcrt.putwch('\r') 115 msvcrt.putwch('\n') 116 return pw 117 118 119def fallback_getpass(prompt='Password: ', stream=None): 120 import warnings 121 warnings.warn("Can not control echo on the terminal.", GetPassWarning, 122 stacklevel=2) 123 if not stream: 124 stream = sys.stderr 125 print("Warning: Password input may be echoed.", file=stream) 126 return _raw_input(prompt, stream) 127 128 129def _raw_input(prompt="", stream=None, input=None): 130 # This doesn't save the string in the GNU readline history. 131 if not stream: 132 stream = sys.stderr 133 if not input: 134 input = sys.stdin 135 prompt = str(prompt) 136 if prompt: 137 try: 138 stream.write(prompt) 139 except UnicodeEncodeError: 140 # Use replace error handler to get as much as possible printed. 141 prompt = prompt.encode(stream.encoding, 'replace') 142 prompt = prompt.decode(stream.encoding) 143 stream.write(prompt) 144 stream.flush() 145 # NOTE: The Python C API calls flockfile() (and unlock) during readline. 146 line = input.readline() 147 if not line: 148 raise EOFError 149 if line[-1] == '\n': 150 line = line[:-1] 151 return line 152 153 154def getuser(): 155 """Get the username from the environment or password database. 156 157 First try various environment variables, then the password 158 database. This works on Windows as long as USERNAME is set. 159 Any failure to find a username raises OSError. 160 161 .. versionchanged:: 3.13 162 Previously, various exceptions beyond just :exc:`OSError` 163 were raised. 164 """ 165 166 for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'): 167 user = os.environ.get(name) 168 if user: 169 return user 170 171 try: 172 import pwd 173 return pwd.getpwuid(os.getuid())[0] 174 except (ImportError, KeyError) as e: 175 raise OSError('No username set in the environment') from e 176 177 178# Bind the name getpass to the appropriate function 179try: 180 import termios 181 # it's possible there is an incompatible termios from the 182 # McMillan Installer, make sure we have a UNIX-compatible termios 183 termios.tcgetattr, termios.tcsetattr 184except (ImportError, AttributeError): 185 try: 186 import msvcrt 187 except ImportError: 188 getpass = fallback_getpass 189 else: 190 getpass = win_getpass 191else: 192 getpass = unix_getpass 193