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 Authors: Piers Lauder (original)
7 Guido van Rossum (Windows support and cleanup)
11 def getpass(prompt
='Password: '):
12 """Prompt for a password, with echo turned off.
14 Restore terminal settings at end.
16 On Windows, this calls win_getpass(prompt) which uses the
17 msvcrt module to get the same effect.
19 On the Mac EasyDialogs.AskPassword is used, if available.
25 fd
= sys
.stdin
.fileno()
27 return default_getpass(prompt
)
29 import termios
, TERMIOS
35 from EasyDialogs
import AskPassword
37 return default_getpass(prompt
)
39 return AskPassword(prompt
)
41 return win_getpass(prompt
)
43 old
= termios
.tcgetattr(fd
) # a copy to save
46 new
[3] = new
[3] & ~TERMIOS
.ECHO
# 3 == 'lflags'
48 termios
.tcsetattr(fd
, TERMIOS
.TCSADRAIN
, new
)
49 passwd
= _raw_input(prompt
)
51 termios
.tcsetattr(fd
, TERMIOS
.TCSADRAIN
, old
)
53 sys
.stdout
.write('\n')
57 def win_getpass(prompt
='Password: '):
58 """Prompt for password with echo off, using Windows getch()."""
65 if c
== '\r' or c
== '\n':
68 raise KeyboardInterrupt
78 def default_getpass(prompt
='Password: '):
79 return _raw_input(prompt
)
82 def _raw_input(prompt
=""):
83 # A raw_input() replacement that doesn't save the string in the
84 # GNU readline history.
88 sys
.stdout
.write(prompt
)
89 line
= sys
.stdin
.readline()
98 """Get the username from the environment or password database.
100 First try various environment variables, then the password
101 database. This works on Windows as long as USERNAME is set.
107 for name
in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
108 user
= os
.environ
.get(name
)
112 # If this fails, the exception will "explain" why
114 return pwd
.getpwuid(os
.getuid())[0]