1 """Utilities to get a password and/or the current user name.
3 getpass(prompt) - prompt for a password, with echo turned off
4 getuser() - get the user name from the environment or password database
6 On Windows, the msvcrt module will be used.
7 On the Mac EasyDialogs.AskPassword is used, if available.
11 # Authors: Piers Lauder (original)
12 # Guido van Rossum (Windows support and cleanup)
16 def unix_getpass(prompt
='Password: '):
17 """Prompt for a password, with echo turned off.
19 Restore terminal settings at end.
23 fd
= sys
.stdin
.fileno()
25 return default_getpass(prompt
)
27 getpass
= default_getpass
28 old
= termios
.tcgetattr(fd
) # a copy to save
31 new
[3] = new
[3] & ~TERMIOS
.ECHO
# 3 == 'lflags'
33 termios
.tcsetattr(fd
, TERMIOS
.TCSADRAIN
, new
)
34 passwd
= _raw_input(prompt
)
36 termios
.tcsetattr(fd
, TERMIOS
.TCSADRAIN
, old
)
38 sys
.stdout
.write('\n')
42 def win_getpass(prompt
='Password: '):
43 """Prompt for password with echo off, using Windows getch()."""
50 if c
== '\r' or c
== '\n':
53 raise KeyboardInterrupt
63 def default_getpass(prompt
='Password: '):
64 print "Warning: Problem with getpass. Passwords may be echoed."
65 return _raw_input(prompt
)
68 def _raw_input(prompt
=""):
69 # A raw_input() replacement that doesn't save the string in the
70 # GNU readline history.
74 sys
.stdout
.write(prompt
)
75 line
= sys
.stdin
.readline()
84 """Get the username from the environment or password database.
86 First try various environment variables, then the password
87 database. This works on Windows as long as USERNAME is set.
93 for name
in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
94 user
= os
.environ
.get(name
)
98 # If this fails, the exception will "explain" why
100 return pwd
.getpwuid(os
.getuid())[0]
102 # Bind the name getpass to the appropriate function
104 import termios
, TERMIOS
110 from EasyDialogs
import AskPassword
112 getpass
= default_getpass
114 getpass
= AskPassword
116 getpass
= win_getpass
118 getpass
= unix_getpass