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
相关推荐
啊巴矲2 分钟前
小白从零开始勇闯人工智能:计算机视觉初级篇(初识Opencv中)
人工智能·opencv·计算机视觉
代码游侠8 分钟前
学习笔记——ESP8266 WiFi模块
服务器·c语言·开发语言·数据结构·算法
0和1的舞者9 分钟前
Python 中四种核心数据结构的用途和嵌套逻辑
数据结构·python·学习·知识
weixin_4624462310 分钟前
Python 使用 PyQt5 + Pandas 实现 Excel(xlsx)批量合并工具(带图形界面)
python·qt·pandas
Hello.Reader11 分钟前
PyFlink Configuration 一次讲透怎么配、配哪些、怎么“调得快且稳”
运维·服务器·python·flink
行者9613 分钟前
Flutter跨平台开发适配OpenHarmony:进度条组件的深度实践
开发语言·前端·flutter·harmonyos·鸿蒙
云和数据.ChenGuang14 分钟前
Uvicorn 是 **Python 生态中用于运行异步 Web 应用的 ASGI 服务器**
服务器·前端·人工智能·python·机器学习
Hello.Reader14 分钟前
PyFlink Table API / DataStream API / UDF / 依赖管理 / 运行时模式一篇打通(含示例代码与避坑)
python·flink
DYS_房东的猫17 分钟前
《 C++ 零基础入门教程》第3章:结构体与类 —— 用面向对象组织代码
开发语言·c++
hui函数19 分钟前
Python系列Bug修复|如何解决 pip install -r requirements.txt 私有仓库认证失败 401 Unauthorized 问题
python·bug·pip