[Python becomes a steel] Implementing a password logger using Python

foreword

Implements a plugin for a black window to encrypt input strings using Python.
You can encapsulate it in a function and call the function to return the input string.
The specific effects are as follows:
insert image description here
back-deletion can be achieved.

Implementation ideas (you can see it with python or not):

  • To accept input characters (must have no echo when receiving) you can use getch()
  • Determine whether the received character is a carriage return (\n) [the carriage return indicates the end of entering the password]
  • Determine whether the character is the delete key (\b)
    [If it is \b, you need to back the cursor and delete the data at the original position. Other languages ​​can assign an initial value to the position]
  • Other characters print * and add the data to the list to be returned

Introduce some points in the code that may cause confusion

  • getch: This getch is a little different from the one in c\c++. What this gets is a bytecode, which needs to be decoded to get a string.
  • \b \b: We all know that \b is the backspace key in the ASCII table, and its corresponding value is 8, so use ord() to convert it when inputting
    \b is backspace, then \b \b is to use a space to convert the original character After overwriting, move the cursor to the original position.
  • sys.stdout.flush(): If you enter the password without this sentence, it will only be displayed when you press the Enter key, that is, there is no
    way to display * or delete * synchronously. Adding this sentence means to refresh the buffer. I don't know exactly why. This happened occasionally when I wrote small C++ projects before. Just refresh the buffer, so when I encountered this kind of problem, I first thought of refreshing the buffer.
  • Everyone should know the rest. After all, those who know python can handle some logic. (code is below)

source code

from msvcrt import getch
import sys


sys.stdout.write("请输入您的密码:")
sys.stdout.flush()
passwd=[]
while True:
    n=getch().decode()
    if ord(n)==13:
        break
    else:
        if ord(n)==8 and len(passwd)!=0:
            print('\b \b',end="")
            passwd.pop()
        elif ord(n)==8 and len(passwd)==0:
            pass
        else:
            print('*',end="")
            passwd.append(n)
    sys.stdout.flush()
print()
print(passwd)

insert image description here

Guess you like

Origin blog.csdn.net/apple_51931783/article/details/124035353