Welcome, guest | Sign In | My Account | Store | Cart

adding the ability to display a password masking character of the programmer's choice

Python, 46 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# created by https://github.com/kingmak

import sys, msvcrt

def getpass(prompt = 'Password: ', hideChar = ' '):

    count = 0
    password = ''
    
    for char in prompt:
        msvcrt.putch(char)# cuz password, be trouble
        
    while True:
        char = msvcrt.getch()
        
        if char == '\r' or char == '\n':
            break
        
        if char == '\003':
            raise KeyboardInterrupt # ctrl + c

        if char == '\b':
            count -= 1
            password = password[:-1]

            if count >= 0:
                msvcrt.putch('\b')
                msvcrt.putch(' ')
                msvcrt.putch('\b')
            
        else:
            if count < 0:
                count = 0
                
            count += 1
            password += char
            msvcrt.putch(hideChar)
            
    msvcrt.putch('\r')
    msvcrt.putch('\n')
    
    return "'%s'" % password if password != '' else "''"

# password = getpass('Password: ', '*')
password = getpass(hideChar = '*')
raw_input('pass = ' + password)

I wanted to display a password masking character when I was using getpass.getpass to get a password from the user. I believe its just a bit more helpful to see how many characters I have typed in the console and how many spaces I want to backspace if needed.

1 comment

KingMak (author) 8 years, 2 months ago  # | flag

By the way, for now this is only for windows