Windows11桌面解锁守护脚本

使用python程序加bat一键运行脚本,妈妈再也不用担心我的电脑桌面了

复制代码
python 复制代码
import os
import time
import cv2
import pyautogui
import psutil
from datetime import datetime

class UnlockMonitor:
    def __init__(self):
        """初始化监控器"""
        self.save_dir = os.path.dirname(os.path.abspath(__file__))
        self.log_file = os.path.join(self.save_dir, "unlock_capture_log.txt")
        self.last_state = self.is_locked()
        self.running = True
        
    def log_message(self, message):
        """记录日志到文件和终端"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = f"[{timestamp}] {message}"
        print(log_entry)
        
        try:
            with open(self.log_file, "a", encoding="utf-8") as f:
                f.write(log_entry + "\n")
        except Exception as e:
            print(f"[{timestamp}] 写入日志失败: {str(e)}")

    def is_camera_available(self):
        """检查摄像头是否可用"""
        try:
            cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
            if not cap.isOpened():
                return False
            cap.release()
            return True
        except Exception as e:
            self.log_message(f"摄像头检测异常: {str(e)}")
            return False

    def capture_camera(self):
        """直接拍照(不对图像做任何处理)"""
        timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        camera_path = os.path.join(self.save_dir, f"camera_{timestamp}.jpg")
        
        try:
            cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
            
            # 基本摄像头设置
            cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
            cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
            cap.set(cv2.CAP_PROP_AUTOFOCUS, 1)  # 启用自动对焦
            
            # 等待摄像头对焦(2秒)
            time.sleep(2)
            
            if not cap.isOpened():
                self.log_message("无法打开摄像头")
                return
                
            # 直接拍摄单帧
            ret, frame = cap.read()
            cap.release()
            
            if ret:
                cv2.imwrite(camera_path, frame)
                self.log_message(f"拍照保存至: {camera_path}")
            else:
                self.log_message("摄像头读取失败")
                
        except Exception as e:
            self.log_message(f"拍照异常: {str(e)}")

    def capture_screenshot(self):
        """截屏"""
        timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        screenshot_path = os.path.join(self.save_dir, f"screenshot_{timestamp}.png")
        
        try:
            screenshot = pyautogui.screenshot()
            screenshot.save(screenshot_path)
            self.log_message(f"截屏保存至: {screenshot_path}")
        except Exception as e:
            self.log_message(f"截屏失败: {str(e)}")

    def is_already_running(self):
        """检查是否已有相同进程在运行"""
        current_pid = os.getpid()
        script_name = os.path.basename(__file__)
        
        for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
            try:
                if (proc.info['pid'] != current_pid and 
                    proc.info['cmdline'] and 
                    script_name in ' '.join(proc.info['cmdline'])):
                    return True
            except (psutil.NoSuchProcess, psutil.AccessDenied, KeyError):
                continue
        return False

    def is_locked(self):
        """检查系统是否处于锁定状态"""
        try:
            for proc in psutil.process_iter(['name']):
                if proc.info['name'] == 'LogonUI.exe':
                    return True
            return False
        except Exception:
            return False

    def run(self):
        """主监控循环"""
        if self.is_already_running():
            self.log_message("已有实例运行,退出当前进程")
            return
        
        self.log_message("===== 解锁监控服务启动 =====")
        self.log_message(f"初始状态: {'锁定' if self.last_state else '解锁'}")
        
        try:
            while self.running:
                current_state = self.is_locked()
                
                # 检测解锁事件
                if self.last_state and not current_state:
                    self.log_message("检测到解锁事件,开始捕获...")
                    
                    if self.is_camera_available():
                        self.capture_camera()
                    
                    self.capture_screenshot()
                
                self.last_state = current_state
                time.sleep(1)  # 检测间隔
                
        except KeyboardInterrupt:
            self.log_message("服务被用户中断")
        except Exception as e:
            self.log_message(f"服务异常: {str(e)}")
        finally:
            self.log_message("===== 监控服务停止 =====")

if __name__ == '__main__':
    monitor = UnlockMonitor()
    monitor.run()
复制代码
bash 复制代码
@echo off
chcp 65001 > nul
title 解锁拍照监控服务
color 0A

:: 设置循环标志
set RESTART_COUNT=0

:restart
echo 正在启动解锁拍照监控服务... (第%RESTART_COUNT%次启动)
echo 按 Ctrl+C 停止服务

:: 设置Python路径(根据您的环境修改)
set PYTHON_PATH="C:\Users\lhyyds\.conda\envs\hust\python.exe"

:: 设置脚本路径
set SCRIPT_PATH="%~dp0wake_monitor.py"

:: 启动Python脚本
%PYTHON_PATH% %SCRIPT_PATH%

:: 检查是否需要重启
set /a RESTART_COUNT+=1
echo 服务意外停止,5秒后自动重启...
timeout /t 5 /nobreak >nul
goto restart

echo 服务已手动停止
pause
相关推荐
醉方休3 小时前
python 自动化在web领域应用
python
liulilittle3 小时前
Unix/Linux 平台通过 IP 地址获取接口名的 C++ 实现
linux·开发语言·c++·tcp/ip·unix·编程语言
Source.Liu3 小时前
【Python基础】 18 Rust 与 Python print 函数完整对比笔记
笔记·python·rust
Nerd Nirvana3 小时前
C++编程——异步处理、事件驱动编程和策略模式
开发语言·c++·策略模式·嵌入式开发·事件驱动·异步处理
大模型真好玩3 小时前
大模型工程面试经典(五)—大模型专业领域微调数据集如何构建?
人工智能·python·面试
UrbanJazzerati3 小时前
Python正则表达式匹配和替换详细指南
python·面试
怒码ing4 小时前
List<?>和List<Object>区别
windows·python·list
那雨倾城4 小时前
PiscCode轨迹跟踪Mediapipe + OpenCV进阶:速度估算
图像处理·人工智能·python·opencv·计算机视觉
闻道且行之4 小时前
嵌入式|Linux中打开视频流的两种方式V4l2和opencv
linux·笔记·opencv·嵌入式
2501_920047034 小时前
bash自带的切片操作
开发语言·python·bash