blob: be7a2f9049b769aa51148088b0410f505ed8b228 [file] [log] [blame]
Guido van Rossumb5903ac1998-04-09 20:37:16 +00001"""Utilities to get a password and/or the current user name.
2
3getpass(prompt) - prompt for a password, with echo turned off
4getuser() - get the user name from the environment or password database
5
6Authors: Piers Lauder (original)
7 Guido van Rossum (Windows support and cleanup)
8"""
9
10
11def getpass(prompt='Password: '):
12 """Prompt for a password, with echo turned off.
13
14 Restore terminal settings at end.
15
16 On Windows, this calls win_getpass(prompt) which uses the
17 msvcrt module to get the same effect.
18
19 """
20
21 import sys
22 try:
23 import termios, TERMIOS
24 except ImportError:
Guido van Rossumfb9b7fd1998-04-13 20:22:21 +000025 try:
26 import msvcrt
27 except ImportError:
28 return default_getpass(prompt)
29 else:
30 return win_getpass(prompt)
Guido van Rossumb5903ac1998-04-09 20:37:16 +000031
32 fd = sys.stdin.fileno()
33 old = termios.tcgetattr(fd) # a copy to save
34 new = old[:]
35
36 new[3] = new[3] & ~TERMIOS.ECHO # 3 == 'lflags'
37 try:
38 termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new)
Guido van Rossum1a7bab01998-07-28 19:28:43 +000039 passwd = _raw_input(prompt)
Guido van Rossumb5903ac1998-04-09 20:37:16 +000040 finally:
41 termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old)
42
43 sys.stdout.write('\n')
44 return passwd
45
46
47def win_getpass(prompt='Password: '):
48 """Prompt for password with echo off, using Windows getch()."""
49 import msvcrt
50 for c in prompt:
51 msvcrt.putch(c)
52 pw = ""
53 while 1:
54 c = msvcrt.getch()
55 if c == '\r' or c == '\n':
56 break
Guido van Rossumc3da02e1998-06-12 14:28:38 +000057 if c == '\003':
58 raise KeyboardInterrupt
Guido van Rossumb5903ac1998-04-09 20:37:16 +000059 if c == '\b':
60 pw = pw[:-1]
61 else:
62 pw = pw + c
63 msvcrt.putch('\r')
64 msvcrt.putch('\n')
65 return pw
66
67
Guido van Rossumfb9b7fd1998-04-13 20:22:21 +000068def default_getpass(prompt='Password: '):
Guido van Rossum1a7bab01998-07-28 19:28:43 +000069 return _raw_input(prompt)
70
71
72def _raw_input(prompt=""):
73 # A raw_input() replacement that doesn't save the string in the
74 # GNU readline history.
75 import sys
76 prompt = str(prompt)
77 if prompt:
78 sys.stdout.write(prompt)
79 line = sys.stdin.readline()
80 if not line:
81 raise EOFError
82 if line[-1] == '\n':
83 line = line[:-1]
84 return line
Guido van Rossumfb9b7fd1998-04-13 20:22:21 +000085
86
Guido van Rossumb5903ac1998-04-09 20:37:16 +000087def getuser():
88 """Get the username from the environment or password database.
89
90 First try various environment variables, then the password
91 database. This works on Windows as long as USERNAME is set.
92
93 """
94
95 import os
96
97 for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
98 user = os.environ.get(name)
99 if user:
100 return user
101
102 # If this fails, the exception will "explain" why
103 import pwd
104 return pwd.getpwuid(os.getuid())[0]