Skip to content

Commit b5903ac

Browse files
committed
Another new utility: getpass() prompts for a password, with echo off.
Also contains getuser(), which returns the username (not prompting though). These work on Unix and Windows!
1 parent f2da4ed commit b5903ac

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

Lib/getpass.py

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""Utilities to get a password and/or the current user name.
2+
3+
getpass(prompt) - prompt for a password, with echo turned off
4+
getuser() - get the user name from the environment or password database
5+
6+
Authors: Piers Lauder (original)
7+
Guido van Rossum (Windows support and cleanup)
8+
"""
9+
10+
11+
def 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:
25+
return win_getpass(prompt)
26+
27+
fd = sys.stdin.fileno()
28+
old = termios.tcgetattr(fd) # a copy to save
29+
new = old[:]
30+
31+
new[3] = new[3] & ~TERMIOS.ECHO # 3 == 'lflags'
32+
try:
33+
termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new)
34+
try: passwd = raw_input(prompt)
35+
except KeyboardInterrupt: passwd = None
36+
finally:
37+
termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old)
38+
39+
sys.stdout.write('\n')
40+
return passwd
41+
42+
43+
def win_getpass(prompt='Password: '):
44+
"""Prompt for password with echo off, using Windows getch()."""
45+
import msvcrt
46+
for c in prompt:
47+
msvcrt.putch(c)
48+
pw = ""
49+
while 1:
50+
c = msvcrt.getch()
51+
if c == '\r' or c == '\n':
52+
break
53+
if c == '\b':
54+
pw = pw[:-1]
55+
else:
56+
pw = pw + c
57+
msvcrt.putch('\r')
58+
msvcrt.putch('\n')
59+
return pw
60+
61+
62+
def getuser():
63+
"""Get the username from the environment or password database.
64+
65+
First try various environment variables, then the password
66+
database. This works on Windows as long as USERNAME is set.
67+
68+
"""
69+
70+
import os
71+
72+
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
73+
user = os.environ.get(name)
74+
if user:
75+
return user
76+
77+
# If this fails, the exception will "explain" why
78+
import pwd
79+
return pwd.getpwuid(os.getuid())[0]

0 commit comments

Comments
 (0)