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

Gregory P. Smith's avatar
Gregory P. Smith 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 11
On Windows, the msvcrt module will be used.
On the Mac EasyDialogs.AskPassword is used, if available.

12 13
"""

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

Gregory P. Smith's avatar
Gregory P. Smith committed
18
import os, sys, warnings
Skip Montanaro's avatar
Skip Montanaro committed
19

Gregory P. Smith's avatar
Gregory P. Smith committed
20
__all__ = ["getpass","getuser","GetPassWarning"]
21 22


Gregory P. Smith's avatar
Gregory P. Smith committed
23
class GetPassWarning(UserWarning): pass
24

25

Gregory P. Smith's avatar
Gregory P. Smith committed
26 27
def unix_getpass(prompt='Password: ', stream=None):
    """Prompt for a password, with echo turned off.
28

Gregory P. Smith's avatar
Gregory P. Smith committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42
    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.
    """
    fd = None
    tty = None
Tim Peters's avatar
Tim Peters committed
43
    try:
Gregory P. Smith's avatar
Gregory P. Smith committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
        # Always try reading and writing directly on the tty first.
        fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
        tty = os.fdopen(fd, 'w+', 1)
        input = tty
        if not stream:
            stream = tty
    except EnvironmentError, e:
        # If that fails, see if stdin can be controlled.
        try:
            fd = sys.stdin.fileno()
        except:
            passwd = fallback_getpass(prompt, stream)
        input = sys.stdin
        if not stream:
            stream = sys.stderr

    if fd is not None:
        passwd = None
        try:
            old = termios.tcgetattr(fd)     # a copy to save
            new = old[:]
            new[3] &= ~termios.ECHO  # 3 == 'lflags'
            try:
                termios.tcsetattr(fd, termios.TCSADRAIN, new)
                passwd = _raw_input(prompt, stream, input=input)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old)
        except termios.error, e:
            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.
            del input, tty  # clean up unused file objects before blocking
            passwd = fallback_getpass(prompt, stream)
80

81
    stream.write('\n')
Tim Peters's avatar
Tim Peters committed
82
    return passwd
83 84


85
def win_getpass(prompt='Password: ', stream=None):
Tim Peters's avatar
Tim Peters committed
86
    """Prompt for password with echo off, using Windows getch()."""
87
    if sys.stdin is not sys.__stdin__:
Gregory P. Smith's avatar
Gregory P. Smith committed
88
        return fallback_getpass(prompt, stream)
Tim Peters's avatar
Tim Peters committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    import msvcrt
    for c in prompt:
        msvcrt.putch(c)
    pw = ""
    while 1:
        c = msvcrt.getch()
        if c == '\r' or c == '\n':
            break
        if c == '\003':
            raise KeyboardInterrupt
        if c == '\b':
            pw = pw[:-1]
        else:
            pw = pw + c
    msvcrt.putch('\r')
    msvcrt.putch('\n')
    return pw
106 107


Gregory P. Smith's avatar
Gregory P. Smith committed
108 109 110 111 112 113
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 >>stream, "Warning: Password input may be echoed."
114
    return _raw_input(prompt, stream)
115 116


Gregory P. Smith's avatar
Gregory P. Smith committed
117
def _raw_input(prompt="", stream=None, input=None):
Tim Peters's avatar
Tim Peters committed
118 119
    # A raw_input() replacement that doesn't save the string in the
    # GNU readline history.
Gregory P. Smith's avatar
Gregory P. Smith committed
120 121 122 123
    if not stream:
        stream = sys.stderr
    if not input:
        input = sys.stdin
Tim Peters's avatar
Tim Peters committed
124 125
    prompt = str(prompt)
    if prompt:
126
        stream.write(prompt)
Gregory P. Smith's avatar
Gregory P. Smith committed
127 128
        stream.flush()
    line = input.readline()
Tim Peters's avatar
Tim Peters committed
129 130 131 132 133
    if not line:
        raise EOFError
    if line[-1] == '\n':
        line = line[:-1]
    return line
134 135


136
def getuser():
Tim Peters's avatar
Tim Peters committed
137
    """Get the username from the environment or password database.
138

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

Tim Peters's avatar
Tim Peters committed
142
    """
143

Tim Peters's avatar
Tim Peters committed
144
    import os
145

Tim Peters's avatar
Tim Peters committed
146 147 148 149
    for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
        user = os.environ.get(name)
        if user:
            return user
150

Tim Peters's avatar
Tim Peters committed
151 152 153
    # If this fails, the exception will "explain" why
    import pwd
    return pwd.getpwuid(os.getuid())[0]
154 155 156

# Bind the name getpass to the appropriate function
try:
157
    import termios
158 159 160 161
    # 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
162 163 164 165 166 167
    try:
        import msvcrt
    except ImportError:
        try:
            from EasyDialogs import AskPassword
        except ImportError:
Gregory P. Smith's avatar
Gregory P. Smith committed
168
            getpass = fallback_getpass
Tim Peters's avatar
Tim Peters committed
169 170 171 172
        else:
            getpass = AskPassword
    else:
        getpass = win_getpass
173
else:
Tim Peters's avatar
Tim Peters committed
174
    getpass = unix_getpass