如何编写剪贴板监控脚本

wen 实用脚本 28

本文目录导读:

如何编写剪贴板监控脚本

  1. Python 方案(推荐)
  2. 跨平台方案(使用 tkinter 和系统 API)
  3. Windows 专用方案(使用 win32clipboard)
  4. 功能增强版本
  5. 安装依赖
  6. 使用建议

Python 方案(推荐)

基础版(使用 pyperclip)

import pyperclip
import time
from datetime import datetime
class ClipboardMonitor:
    def __init__(self):
        self.last_content = ""
        self.running = True
    def monitor(self):
        print("开始监控剪贴板...")
        while self.running:
            try:
                current_content = pyperclip.paste()
                if current_content != self.last_content:
                    if current_content:  # 忽略空内容
                        self.last_content = current_content
                        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                        print(f"[{timestamp}] 新内容: {current_content[:100]}...")
            except Exception as e:
                print(f"错误: {e}")
            time.sleep(0.5)  # 每0.5秒检查一次
    def stop(self):
        self.running = False
# 使用示例
if __name__ == "__main__":
    monitor = ClipboardMonitor()
    try:
        monitor.monitor()
    except KeyboardInterrupt:
        print("停止监控")

高级版(带日志)

import pyperclip
import time
import json
import os
from datetime import datetime
class AdvancedClipboardMonitor:
    def __init__(self, log_file="clipboard_log.json"):
        self.last_content = ""
        self.log_file = log_file
        self.load_history()
    def load_history(self):
        """加载历史记录"""
        if os.path.exists(self.log_file):
            with open(self.log_file, 'r', encoding='utf-8') as f:
                self.history = json.load(f)
        else:
            self.history = []
    def save_to_history(self, content):
        """保存到历史记录"""
        entry = {
            "timestamp": datetime.now().isoformat(),
            "content": content,
            "length": len(content)
        }
        self.history.append(entry)
        # 只保留最近100条记录
        if len(self.history) > 100:
            self.history = self.history[-100:]
        with open(self.log_file, 'w', encoding='utf-8') as f:
            json.dump(self.history, f, ensure_ascii=False, indent=2)
    def monitor(self):
        print(f"开始监控剪贴板 (日志保存到 {self.log_file})")
        while True:
            try:
                current_content = pyperclip.paste()
                if current_content != self.last_content and current_content:
                    self.last_content = current_content
                    # 过滤掉空或单字符内容
                    if len(current_content) > 1:
                        self.save_to_history(current_content)
                        print(f"捕获新内容: {current_content[:50]}...")
            except Exception as e:
                print(f"错误: {e}")
            time.sleep(0.3)

跨平台方案(使用 tkinter 和系统 API)

import tkinter as tk
import threading
import time
class CrossPlatformClipboardMonitor:
    def __init__(self):
        self.root = tk.Tk()
        self.root.withdraw()  # 隐藏主窗口
        self.last_content = ""
    def get_clipboard(self):
        try:
            return self.root.clipboard_get()
        except:
            return ""
    def monitor(self):
        while True:
            current = self.get_clipboard()
            if current and current != self.last_content:
                self.last_content = current
                print(f"检测到: {current}")
            time.sleep(0.5)
    def start(self):
        monitor_thread = threading.Thread(target=self.monitor, daemon=True)
        monitor_thread.start()
        self.root.mainloop()
# 使用
monitor = CrossPlatformClipboardMonitor()
monitor.start()

Windows 专用方案(使用 win32clipboard)

import win32clipboard
import time
class WindowsClipboardMonitor:
    def __init__(self):
        self.last_content = ""
    def get_clipboard_text(self):
        try:
            win32clipboard.OpenClipboard()
            data = win32clipboard.GetClipboardData()
            win32clipboard.CloseClipboard()
            return data
        except:
            return ""
    def monitor(self):
        print("Windows 剪贴板监控启动...")
        while True:
            current = self.get_clipboard_text()
            if current and current != self.last_content:
                self.last_content = current
                print(f"新内容: {current[:100]}")
            time.sleep(0.2)

功能增强版本

import pyperclip
import time
import re
from collections import deque
class SmartClipboardMonitor:
    def __init__(self, max_history=50):
        self.history = deque(maxlen=max_history)
        self.last_content = ""
        self.filters = []
    def add_filter(self, pattern, callback):
        """添加过滤规则"""
        self.filters.append((re.compile(pattern), callback))
    def should_ignore(self, content):
        """检查是否应该忽略"""
        # 忽略密码字段
        if "password" in content.lower():
            return True
        # 忽略过长的内容
        if len(content) > 10000:
            return True
        return False
    def process_content(self, content):
        """处理内容"""
        if self.should_ignore(content):
            return
        # 应用过滤器
        for pattern, callback in self.filters:
            if pattern.search(content):
                callback(content)
        # 保存到历史
        self.history.append({
            'time': time.time(),
            'content': content[:200]  # 只保存前200字符
        })
    def monitor(self):
        while True:
            try:
                current = pyperclip.paste()
                if current != self.last_content and current:
                    self.last_content = current
                    self.process_content(current)
            except Exception as e:
                print(f"监控错误: {e}")
            time.sleep(0.3)
# 使用示例
monitor = SmartClipboardMonitor()
monitor.add_filter(r'\b\d{3}-\d{2}-\d{4}\b', lambda x: print(f"发现SSN: {x}"))
monitor.monitor()

安装依赖

# 基础版本
pip install pyperclip
# Windows 版本
pip install pywin32
# 增强版本
pip install pyperclip pillow

使用建议

  1. 安全考虑

    • 不要监控敏感信息(密码、信用卡号)
    • 添加加密存储机制
    • 考虑添加用户确认流程
  2. 性能优化

    • 设置合理的检查间隔(0.2-1秒)
    • 避免频繁IO操作
    • 使用缓存机制
  3. 实际应用

    • 代码片段收集器
    • 文本格式转换工具
    • 剪贴板历史管理器

选择哪种方案取决于你的具体需求和使用场景,Python + pyperclip 是最简单通用的选择。

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