getpass.py 5.8 KB

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