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
相关推荐
tanyongxi667 分钟前
C++ Map 和 Set 详解:从原理到实战应用
开发语言·c++
飒飒真编程16 分钟前
C++类模板继承部分知识及测试代码
开发语言·c++·算法
看到我,请让我去学习1 小时前
OpenCV 图像进阶处理:特征提取与车牌识别深度解析
人工智能·opencv·计算机视觉
apihz1 小时前
通用图片搜索-搜狗源免费API接口使用指南
android·java·python·php·音视频
博睿谷IT99_1 小时前
华为数据通信网络基础
开发语言·华为·php·华为认证
爱吃面条的猿1 小时前
pycharm中自动补全方法返回变量
ide·python·pycharm
蓝桉(努力版)1 小时前
MATLAB可视化5:华夫图(饼图的平替可以表示种类的分布,附有完整代码详细讲解)(求个关注、点赞和收藏)(对配色不满意可以自己调节配色,附调色教程)
开发语言·数学建模·matlab·信息可视化·matlab可视化
倔强青铜三1 小时前
苦练Python第15天:Lambda函数——Python的匿名一行杀器
人工智能·python·面试
艾莉丝努力练剑1 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(五)
c语言·开发语言·数据结构·学习·算法
云空2 小时前
《QtPy:Python与Qt的完美桥梁》
开发语言·python·qt·pyqt