blob: 44e78c264be2e145ddea47b155a93a204ad57681 [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:
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
43def 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
62def 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]