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

getpass(prompt) - prompt for a password, with echo turned off
getuser() - get the user name from the environment or password database

6 7 8
On Windows, the msvcrt module will be used.
On the Mac EasyDialogs.AskPassword is used, if available.

9 10
"""

11 12 13
# Authors: Piers Lauder (original)
#          Guido van Rossum (Windows support and cleanup)

14
import sys
15

Skip Montanaro's avatar
Skip Montanaro committed
16 17
__all__ = ["getpass","getuser"]

18
def unix_getpass(prompt='Password: '):
Tim Peters's avatar
Tim Peters committed
19
    """Prompt for a password, with echo turned off.
20

Tim Peters's avatar
Tim Peters committed
21 22
    Restore terminal settings at end.
    """
23

Tim Peters's avatar
Tim Peters committed
24 25 26 27
    try:
        fd = sys.stdin.fileno()
    except:
        return default_getpass(prompt)
28

Tim Peters's avatar
Tim Peters committed
29 30
    old = termios.tcgetattr(fd)     # a copy to save
    new = old[:]
31

32
    new[3] = new[3] & ~termios.ECHO # 3 == 'lflags'
Tim Peters's avatar
Tim Peters committed
33
    try:
34
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
Tim Peters's avatar
Tim Peters committed
35 36
        passwd = _raw_input(prompt)
    finally:
37
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
38

Tim Peters's avatar
Tim Peters committed
39 40
    sys.stdout.write('\n')
    return passwd
41 42 43


def win_getpass(prompt='Password: '):
Tim Peters's avatar
Tim Peters committed
44
    """Prompt for password with echo off, using Windows getch()."""
45 46
    if sys.stdin is not sys.__stdin__:
        return default_getpass(prompt)
Tim Peters's avatar
Tim Peters committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    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
64 65


66
def default_getpass(prompt='Password: '):
Tim Peters's avatar
Tim Peters committed
67 68
    print "Warning: Problem with getpass. Passwords may be echoed."
    return _raw_input(prompt)
69 70 71


def _raw_input(prompt=""):
Tim Peters's avatar
Tim Peters committed
72 73 74 75 76 77 78 79 80 81 82
    # A raw_input() replacement that doesn't save the string in the
    # GNU readline history.
    prompt = str(prompt)
    if prompt:
        sys.stdout.write(prompt)
    line = sys.stdin.readline()
    if not line:
        raise EOFError
    if line[-1] == '\n':
        line = line[:-1]
    return line
83 84


85
def getuser():
Tim Peters's avatar
Tim Peters committed
86
    """Get the username from the environment or password database.
87

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

Tim Peters's avatar
Tim Peters committed
91
    """
92

Tim Peters's avatar
Tim Peters committed
93
    import os
94

Tim Peters's avatar
Tim Peters committed
95 96 97 98
    for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
        user = os.environ.get(name)
        if user:
            return user
99

Tim Peters's avatar
Tim Peters committed
100 101 102
    # If this fails, the exception will "explain" why
    import pwd
    return pwd.getpwuid(os.getuid())[0]
103 104 105

# Bind the name getpass to the appropriate function
try:
106
    import termios
107 108 109 110
    # 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
111 112 113 114 115 116 117 118 119 120 121
    try:
        import msvcrt
    except ImportError:
        try:
            from EasyDialogs import AskPassword
        except ImportError:
            getpass = default_getpass
        else:
            getpass = AskPassword
    else:
        getpass = win_getpass
122
else:
Tim Peters's avatar
Tim Peters committed
123
    getpass = unix_getpass