getpass.py 5.85 KB
Newer Older
1 2
"""Utilities to get a password and/or the current user name.

Christian Heimes's avatar
Christian Heimes committed
3 4 5 6 7
getpass(prompt[, stream]) - Prompt for a password, with echo turned off.
getuser() - Get the user name from the environment or password database.

GetPassWarning - This UserWarning is issued when getpass() cannot prevent
                 echoing of the password contents while reading.
8

9 10
On Windows, the msvcrt module will be used.

11 12
"""

13 14
# Authors: Piers Lauder (original)
#          Guido van Rossum (Windows support and cleanup)
Christian Heimes's avatar
Christian Heimes committed
15
#          Gregory P. Smith (tty support & GetPassWarning)
16

17 18 19 20 21
import contextlib
import io
import os
import sys
import warnings
22

Christian Heimes's avatar
Christian Heimes committed
23
__all__ = ["getpass","getuser","GetPassWarning"]
Skip Montanaro's avatar
Skip Montanaro committed
24

25

Christian Heimes's avatar
Christian Heimes committed
26
class GetPassWarning(UserWarning): pass
27 28


Christian Heimes's avatar
Christian Heimes committed
29 30
def unix_getpass(prompt='Password: ', stream=None):
    """Prompt for a password, with echo turned off.
31

Christian Heimes's avatar
Christian Heimes committed
32 33 34 35 36 37 38 39 40 41 42 43
    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.
    Returns:
      The seKr3t input.
    Raises:
      EOFError: If our input tty or stdin was closed.
      GetPassWarning: When we were unable to turn echo off on the input.

    Always restores terminal settings before returning.
    """
44
    passwd = None
45
    with contextlib.ExitStack() as stack:
Christian Heimes's avatar
Christian Heimes committed
46
        try:
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
            # Always try reading and writing directly on the tty first.
            fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
            tty = io.FileIO(fd, 'w+')
            stack.enter_context(tty)
            input = io.TextIOWrapper(tty)
            stack.enter_context(input)
            if not stream:
                stream = input
        except OSError as e:
            # If that fails, see if stdin can be controlled.
            stack.close()
            try:
                fd = sys.stdin.fileno()
            except (AttributeError, ValueError):
                fd = None
                passwd = fallback_getpass(prompt, stream)
            input = sys.stdin
            if not stream:
                stream = sys.stderr

        if fd is not None:
Christian Heimes's avatar
Christian Heimes committed
68
            try:
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
                old = termios.tcgetattr(fd)     # a copy to save
                new = old[:]
                new[3] &= ~termios.ECHO  # 3 == 'lflags'
                tcsetattr_flags = termios.TCSAFLUSH
                if hasattr(termios, 'TCSASOFT'):
                    tcsetattr_flags |= termios.TCSASOFT
                try:
                    termios.tcsetattr(fd, tcsetattr_flags, new)
                    passwd = _raw_input(prompt, stream, input=input)
                finally:
                    termios.tcsetattr(fd, tcsetattr_flags, old)
                    stream.flush()  # issue7208
            except termios.error:
                if passwd is not None:
                    # _raw_input succeeded.  The final tcsetattr failed.  Reraise
                    # instead of leaving the terminal in an unknown state.
                    raise
                # We can't control the tty or stdin.  Give up and use normal IO.
                # fallback_getpass() raises an appropriate warning.
                if stream is not input:
                    # clean up unused file objects before blocking
                    stack.close()
                passwd = fallback_getpass(prompt, stream)

        stream.write('\n')
        return passwd
95 96


97
def win_getpass(prompt='Password: ', stream=None):
Tim Peters's avatar
Tim Peters committed
98
    """Prompt for password with echo off, using Windows getch()."""
99
    if sys.stdin is not sys.__stdin__:
Christian Heimes's avatar
Christian Heimes committed
100
        return fallback_getpass(prompt, stream)
101

Tim Peters's avatar
Tim Peters committed
102
    for c in prompt:
103
        msvcrt.putwch(c)
Tim Peters's avatar
Tim Peters committed
104 105
    pw = ""
    while 1:
106
        c = msvcrt.getwch()
Tim Peters's avatar
Tim Peters committed
107 108 109 110 111 112 113 114
        if c == '\r' or c == '\n':
            break
        if c == '\003':
            raise KeyboardInterrupt
        if c == '\b':
            pw = pw[:-1]
        else:
            pw = pw + c
115 116
    msvcrt.putwch('\r')
    msvcrt.putwch('\n')
Tim Peters's avatar
Tim Peters committed
117
    return pw
118 119


Christian Heimes's avatar
Christian Heimes committed
120 121 122 123 124 125
def fallback_getpass(prompt='Password: ', stream=None):
    warnings.warn("Can not control echo on the terminal.", GetPassWarning,
                  stacklevel=2)
    if not stream:
        stream = sys.stderr
    print("Warning: Password input may be echoed.", file=stream)
126
    return _raw_input(prompt, stream)
127 128


Christian Heimes's avatar
Christian Heimes committed
129
def _raw_input(prompt="", stream=None, input=None):
130
    # This doesn't save the string in the GNU readline history.
Christian Heimes's avatar
Christian Heimes committed
131 132 133 134
    if not stream:
        stream = sys.stderr
    if not input:
        input = sys.stdin
Tim Peters's avatar
Tim Peters committed
135 136
    prompt = str(prompt)
    if prompt:
137 138 139
        try:
            stream.write(prompt)
        except UnicodeEncodeError:
140
            # Use replace error handler to get as much as possible printed.
141 142 143
            prompt = prompt.encode(stream.encoding, 'replace')
            prompt = prompt.decode(stream.encoding)
            stream.write(prompt)
144
        stream.flush()
145
    # NOTE: The Python C API calls flockfile() (and unlock) during readline.
Christian Heimes's avatar
Christian Heimes committed
146
    line = input.readline()
Tim Peters's avatar
Tim Peters committed
147 148 149 150 151
    if not line:
        raise EOFError
    if line[-1] == '\n':
        line = line[:-1]
    return line
152 153


154
def getuser():
Tim Peters's avatar
Tim Peters committed
155
    """Get the username from the environment or password database.
156

Tim Peters's avatar
Tim Peters committed
157 158
    First try various environment variables, then the password
    database.  This works on Windows as long as USERNAME is set.
159

Tim Peters's avatar
Tim Peters committed
160
    """
161

Tim Peters's avatar
Tim Peters committed
162 163 164 165
    for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
        user = os.environ.get(name)
        if user:
            return user
166

Tim Peters's avatar
Tim Peters committed
167 168 169
    # If this fails, the exception will "explain" why
    import pwd
    return pwd.getpwuid(os.getuid())[0]
170 171 172

# Bind the name getpass to the appropriate function
try:
173
    import termios
174 175 176 177
    # it's possible there is an incompatible termios from the
    # McMillan Installer, make sure we have a UNIX-compatible termios
    termios.tcgetattr, termios.tcsetattr
except (ImportError, AttributeError):
Tim Peters's avatar
Tim Peters committed
178 179
    try:
        import msvcrt
180
    except ImportError:
181
        getpass = fallback_getpass
Tim Peters's avatar
Tim Peters committed
182 183
    else:
        getpass = win_getpass
184
else:
Tim Peters's avatar
Tim Peters committed
185
    getpass = unix_getpass