getpass.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. """Utilities to get a password and/or the current user name.
  2. getpass(prompt[, stream]) - Prompt for a password, with echo turned off.
  3. getuser() - Get the user name from the environment or password database.
  4. GetPassWarning - This UserWarning is issued when getpass() cannot prevent
  5. echoing of the password contents while reading.
  6. On Windows, the msvcrt module will be used.
  7. On the Mac EasyDialogs.AskPassword is used, if available.
  8. """
  9. # Authors: Piers Lauder (original)
  10. # Guido van Rossum (Windows support and cleanup)
  11. # Gregory P. Smith (tty support & GetPassWarning)
  12. import os, sys, warnings
  13. __all__ = ["getpass","getuser","GetPassWarning"]
  14. class GetPassWarning(UserWarning): pass
  15. def unix_getpass(prompt='Password: ', stream=None):
  16. """Prompt for a password, with echo turned off.
  17. Args:
  18. prompt: Written on stream to ask for the input. Default: 'Password: '
  19. stream: A writable file object to display the prompt. Defaults to
  20. the tty. If no tty is available defaults to sys.stderr.
  21. Returns:
  22. The seKr3t input.
  23. Raises:
  24. EOFError: If our input tty or stdin was closed.
  25. GetPassWarning: When we were unable to turn echo off on the input.
  26. Always restores terminal settings before returning.
  27. """
  28. fd = None
  29. tty = None
  30. try:
  31. # Always try reading and writing directly on the tty first.
  32. fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
  33. tty = os.fdopen(fd, 'w+', 1)
  34. input = tty
  35. if not stream:
  36. stream = tty
  37. except EnvironmentError, e:
  38. # If that fails, see if stdin can be controlled.
  39. try:
  40. fd = sys.stdin.fileno()
  41. except (AttributeError, ValueError):
  42. passwd = fallback_getpass(prompt, stream)
  43. input = sys.stdin
  44. if not stream:
  45. stream = sys.stderr
  46. if fd is not None:
  47. passwd = None
  48. try:
  49. old = termios.tcgetattr(fd) # a copy to save
  50. new = old[:]
  51. new[3] &= ~termios.ECHO # 3 == 'lflags'
  52. tcsetattr_flags = termios.TCSAFLUSH
  53. if hasattr(termios, 'TCSASOFT'):
  54. tcsetattr_flags |= termios.TCSASOFT
  55. try:
  56. termios.tcsetattr(fd, tcsetattr_flags, new)
  57. passwd = _raw_input(prompt, stream, input=input)
  58. finally:
  59. termios.tcsetattr(fd, tcsetattr_flags, old)
  60. stream.flush() # issue7208
  61. except termios.error, e:
  62. if passwd is not None:
  63. # _raw_input succeeded. The final tcsetattr failed. Reraise
  64. # instead of leaving the terminal in an unknown state.
  65. raise
  66. # We can't control the tty or stdin. Give up and use normal IO.
  67. # fallback_getpass() raises an appropriate warning.
  68. del input, tty # clean up unused file objects before blocking
  69. passwd = fallback_getpass(prompt, stream)
  70. stream.write('\n')
  71. return passwd
  72. def win_getpass(prompt='Password: ', stream=None):
  73. """Prompt for password with echo off, using Windows getch()."""
  74. if sys.stdin is not sys.__stdin__:
  75. return fallback_getpass(prompt, stream)
  76. import msvcrt
  77. for c in prompt:
  78. msvcrt.putch(c)
  79. pw = ""
  80. while 1:
  81. c = msvcrt.getch()
  82. if c == '\r' or c == '\n':
  83. break
  84. if c == '\003':
  85. raise KeyboardInterrupt
  86. if c == '\b':
  87. pw = pw[:-1]
  88. else:
  89. pw = pw + c
  90. msvcrt.putch('\r')
  91. msvcrt.putch('\n')
  92. return pw
  93. def fallback_getpass(prompt='Password: ', stream=None):
  94. warnings.warn("Can not control echo on the terminal.", GetPassWarning,
  95. stacklevel=2)
  96. if not stream:
  97. stream = sys.stderr
  98. print >>stream, "Warning: Password input may be echoed."
  99. return _raw_input(prompt, stream)
  100. def _raw_input(prompt="", stream=None, input=None):
  101. # A raw_input() replacement that doesn't save the string in the
  102. # GNU readline history.
  103. if not stream:
  104. stream = sys.stderr
  105. if not input:
  106. input = sys.stdin
  107. prompt = str(prompt)
  108. if prompt:
  109. stream.write(prompt)
  110. stream.flush()
  111. # NOTE: The Python C API calls flockfile() (and unlock) during readline.
  112. line = input.readline()
  113. if not line:
  114. raise EOFError
  115. if line[-1] == '\n':
  116. line = line[:-1]
  117. return line
  118. def getuser():
  119. """Get the username from the environment or password database.
  120. First try various environment variables, then the password
  121. database. This works on Windows as long as USERNAME is set.
  122. """
  123. import os
  124. for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
  125. user = os.environ.get(name)
  126. if user:
  127. return user
  128. # If this fails, the exception will "explain" why
  129. import pwd
  130. return pwd.getpwuid(os.getuid())[0]
  131. # Bind the name getpass to the appropriate function
  132. try:
  133. import termios
  134. # it's possible there is an incompatible termios from the
  135. # McMillan Installer, make sure we have a UNIX-compatible termios
  136. termios.tcgetattr, termios.tcsetattr
  137. except (ImportError, AttributeError):
  138. try:
  139. import msvcrt
  140. except ImportError:
  141. try:
  142. from EasyDialogs import AskPassword
  143. except ImportError:
  144. getpass = fallback_getpass
  145. else:
  146. getpass = AskPassword
  147. else:
  148. getpass = win_getpass
  149. else:
  150. getpass = unix_getpass