2011-10-20 45 views
8

我正在寫與Python Windows下的控制檯程序。
用戶需要登錄到使用程序,當他輸入了密碼,我想他們要回顯爲「*」,而我能得到什麼樣的用戶輸入。
我在標準庫中發現了一個叫getpass模塊的,但它不會迴應任何事情,當你輸入(的Linux等)。
謝謝。如何閱讀在Python控制檯程序回聲密碼「*」?

回答

7

getpass模塊用Python編寫的。你可以很容易地修改它來做到這一點。事實上,這裏是getpass.win_getpass()修改後的版本,你可以只粘貼到您的代碼:

import sys 

def win_getpass(prompt='Password: ', stream=None): 
    """Prompt for password with echo off, using Windows getch().""" 
    import msvcrt 
    for c in prompt: 
     msvcrt.putch(c) 
    pw = "" 
    while 1: 
     c = msvcrt.getch() 
     if c == '\r' or c == '\n': 
      break 
     if c == '\003': 
      raise KeyboardInterrupt 
     if c == '\b': 
      pw = pw[:-1] 
      msvcrt.putch('\b') 
     else: 
      pw = pw + c 
      msvcrt.putch("*") 
    msvcrt.putch('\r') 
    msvcrt.putch('\n') 
    return pw 

你可能想不過重新考慮這個。 Linux方式更好;即使只知道密碼中的字符數量,也是對想要破解它的人的一個重要暗示。

+0

msvcrt.putch('\ b')似乎這不起作用 – wong2

-1

You can use the getpass module.這並不完全回答這個問題,因爲getpass函數時無法正常輸出到控制檯除了提示。原因是它是一個額外的安全層。如果有人在看你的肩膀,他們將無法弄清你的密碼有多長。

這裏有一個如何使用它的一個例子:

from getpass import getpass 
getpass('Enter your password: ') 

這個例子將顯示「請輸入密碼」,然後就可以在鍵入密碼。

+0

'getpass'在原始問題中被提及並被拒絕,因爲它不回顯星號。 – kindall

4

kindall的回答很接近,但是退格並沒有清除星號,退格鍵能夠回到輸入提示之外。

嘗試:

def win_getpass(prompt='Password: ', stream=None): 
    """Prompt for password with echo off, using Windows getch().""" 
    if sys.stdin is not sys.__stdin__: 
     return fallback_getpass(prompt, stream) 
    import msvcrt 
    for c in prompt: 
     msvcrt.putwch(c) 
    pw = "" 
    while 1: 
     c = msvcrt.getwch() 
     if c == '\r' or c == '\n': 
      break 
     if c == '\003': 
      raise KeyboardInterrupt 
     if c == '\b': 
      if pw == '': 
       pass 
      else: 
       pw = pw[:-1] 
       msvcrt.putwch('\b') 
       msvcrt.putwch(" ") 
       msvcrt.putwch('\b') 
     else: 
      pw = pw + c 
      msvcrt.putwch("*") 
    msvcrt.putwch('\r') 
    msvcrt.putwch('\n') 
    return pw 

注意mscvrt.putwch不使用Python 2.x的工作,你需要使用mscvrt.putch代替。