The program runs fine, though it won't save my keystrokes to keylogger.txt
from pynput.keyboard import Key, Listener
keys = []
count = 0
def key_pressed(key):
global keys, count
keys.append(key)
count += 1
print(key)
def write_to_file(keys):
with open("keylogger.txt", "a") as f:
for key in keys:
f.write(str(keys))
if count == 1:
count = 0
write_to_file(keys)
keys = []
with Listener(on_press=key_pressed) as listener:
listener.join()
Where is the problem in my code?
Your write_to_file code never runs. You change the value of count but you don't run write_to_file again. Put a write_to_file call inside key_pressed block and it will happen.
I'm not entirely sure of the "buffering" that's happening in your code, but here's how I would do it:
from pynput.keyboard import Key, Listener
def key_pressed(key):
print(key)
with open("keylogger.txt", "a") as f:
f.write(str(key) + "\n")
with Listener(on_press=key_pressed) as listener:
listener.join()
The if statement in your code executes only once, so your write_to_file function is never called.
Problem is this part of your code.
if count == 1:
count = 0
write_to_file(keys)
keys = []
This block in your code never runs.
If you want to use same format of your code use this. But a simpler approach is attached below
from pynput.keyboard import Key, Listener
keys = []
count = 0
def key_pressed(key):
global keys, count
keys.append(key)
count += 1
print(key)
if count == 1:
count = 0
write_to_file(keys)
keys = []
def write_to_file(keys):
with open("keylogger.txt", "a") as f:
for key in keys:
f.write(str(keys))
with Listener(on_press=key_pressed) as listener:
listener.join()
Another implementation for the same
from pynput.keyboard import Key, Listener
def key_pressed(key):
# Stop listener
if key == Key.esc:
return False
with open("keylogger.txt", "a") as f:
f.write(str(key))
with Listener(on_release=key_pressed) as listener:
listener.join()
Related
I want to print on the console each word in a sentence, but only when the spacebar is pressed by the user, like this: at the begging nothing happens; then the user press the spacebar and the first word appears and stays there; then he/she presses the spacebar again and the second word appears; and so on:
<keypress> This <keypress> is <keypress> my <keypress> sentence.
I've written the code bellow, but I could only make all the words appear simultaneously.
import pynput
from pynput.keyboard import Key, Listener
sentence = 'This is my sentence'
def on_press(key):
if key == Key.space:
i = 0
while True:
print(sentence.split()[i])
i = i + 1
if i == len(sentence.split()):
break
elif key == Key.delete: # Manually stop the process!
return False
with Listener(on_press=on_press) as listener:
listener.join()
Thank you for your help.
import time
from pynput.keyboard import Key, Listener
SENTENCE = 'This is my sentence'
index = 0
stop = False
def on_press(key):
global index, stop
if key == Key.space:
if index < len(SENTENCE.split()):
print(SENTENCE.split()[index])
index += 1
else:
stop = True
elif key == Key.delete: # Manually stop the process!
stop = True
with Listener(on_press=on_press, daemon=True) as listener:
while listener.is_alive() and not stop:
time.sleep(2)
If I press ctrl and alt at the same time, my program does nothing. I want if I press ctrl and alt at the same time python will automatically refresh the page 100 times.
Does anyone know why this isn't working and what I need to change?
from pynput import keyboard
def on_press(key):
if key == keyboard.Key.esc:
return False # stop listener
try:
k = key.char # single-char keys
except Exception as ex:
k = key.name # other keys
if k in ['ctl'+'alt']: # keys of interest
# self.keys.append(k) # store it in global-like variable
print('Key pressed: ' + k)
listener = keyboard.Listener(on_press=on_press)
listener.start() # start to listen on a separate thread
listener.join() # remove if main thread is polling self.keys
I have been testing your example and it seems that the library distinguishes between left and right 'Ctrl' and 'Alt'.
You should also note that only ONE KEY is detected, so the expression 'if k in ['ctl'+'alt']:' will never be TRUE.
If you change it to 'if k in ['ctrl_l', 'alt_l']:' (note that I changed the names of the keys as I said before that every key is different) at least one of them will be recognised. The approach given to achieve your goal is not the right one. Check this approach or something like this:
from pynput import keyboard
# The key combination to check
COMBINATION = {keyboard.Key.ctrl_l, keyboard.Key.alt_l}
# The currently active modifiers
current = set()
def on_press(key):
if key in COMBINATION:
current.add(key)
if all(k in current for k in COMBINATION):
print('PRESSED')
if key == keyboard.Key.esc:
listener.stop()
def on_release(key):
try:
current.remove(key)
except KeyError:
pass
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
While trying to make a keylogger via python, I came across the following error
C:\Users\tahas\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'c:\\Users\\tahas\\OneDrive\\Masaüstü\\AS\\keylogger.py':
[Errno 22] Invalid argument
from pynput.keyboard import Key, Listener
"""
key -> klavye tuşu (esc, space , enter.......)
listener -> klavyeyi dinleyen fonksiyon
"""
count = 0
keys = []
def on_press(key):
global keys, count
keys.append(key)
count += 1
print("{} tuşuna basıldı!".format(str(key)))
if count >10:
write_file(keys)
keys= []
count = 0
def write_file(keys):
with open("logs.txt", "a") as file:
for key in keys:
k = str(key).replace("'", "")
if k.find("space") > 0:
file.write("\n")
elif k.find("Key"):
file.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()
i don't know why i can't open the file can you help me
I want to write a program which counts, how often a key is pressed on my keyboard (e.g. per day). I can use Pynput to recognize a certain keypress, but I'm struggling with the counting part. Here's what I got so far:
from pynput.keyboard import Key, Listener
i = 0
def on_press(key, pressed):
print('{0} pressed'.format(
key))
if pressed({0}):
i = i + 1
def on_release(key):
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
That executes the following error:
TypeError: on_press() missing 1 required positional argument: 'pressed'
I also don't know how to seperate all 26 letters and am not really sure what to do now...does anyone have an idea?
I'm trying to figure this exact problem out myself. To answer what the error wants, it wants you to define the parameter "pressed" in your arguments passed to on_press.
ex.
def on_press(key, pressed=0):
print('{0} pressed'.format(
key))
if pressed({0}):
i = i + 1
your i = 0 above that block is out of scope for the on_press block, and therefore cannot be used.
The problem I'm having is, I can get it to count the keystrokes recursively, however it doesn't stop and goes to the max recursion depth with just one keystroke!
I'll reply again if I make any progress. Good luck to you as well!
--- I figured it out! ---
The following link to another StackOverflow post led me in the right direction:
Checking a specific key with pynput in Python
Here's my code. It will display the character typed and increment the count of keys typed:
from pynput.keyboard import Key, Listener
strokes = 0
def on_press(key):
if key == Key.esc:
return False
print('{0} pressed'.format(
key))
global strokes
strokes += 1
print(strokes)
with Listener(
on_press=on_press) as listener:
listener.join()
I hope this helps!
from pynput import keyboard
c=0
with keyboard.Events() as events:
for event in events:
if event.key == keyboard.Key.esc:
break
elif (str(event)) == "Press(key='1')":
c+=1
print(c)
You can use any keys inside "Press(key='1')" like "Press(key='2')" , "Press(key='q')"
I am running Python 3.8 (Also tested on 2.7). Attached below is code to a keylogger that I created with reference to a video tutorial as I'm fairly new to Python and trying to learn. I am trying to make it where when the space key is pressed, it writes a new line to the file so it tabs down and looks nicer. I've tried a few different things online that I've found however nothing has fixed it. If someone could help me and explain why this doesn't work it would be much appreciated. Thanks and have a great week
# Define imports
import pynput
from pynput.keyboard import Key, Listener
# Define variables for keylogger
count = 0
keys = []
# Function to detect key presses
def on_press(key):
global count, keys
keys.append(key)
count += 1
print(str(key))
if count >= 1:
write_file(str(keys))
keys = []
count = 0
# Function to write the letters to a file
def write_file(keys):
with open("log_test.txt", "a") as f:
for key in keys:
k = str(key).replace("'", "").replace("u", "").replace("]", "").replace(",", "").replace("[", "")
if k.find("space") >= 0: # This is the code to check for space bar press
f.write('\n')
else:
k.find("Key") == -1
f.write(k)
# Detect when a key is released
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
That's because your "k" is not "space", but "s", "p", "a", "c", "e".
Not the most elegant method, but try this:
def on_press(key):
global count, keys
keys.append(key)
count += 1
if count >= 1:
write_file(keys) # don't convert to string here
keys = []
count = 0
def write_file(key):
with open("log_test.txt", "a") as f:
if str(key).find("space") >= 0: # transform to string to find what you want
f.write('\n')
elif str(key).find("Key") == -1: # transform to string to find what you want
# key will come as a list, like this: ['char']
# take the first (and only) element, and it will be like this: 'char'
# then remove the "'" and you'll have your character
key = str(key[0]).replace("'", '') # take only the character, then save it
f.write(key)
When you are checking for space, do this:
if k.find(" ") >= 0: # use plain space " " and not "space"
f.write('\n')