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
相关推荐
csbysj20203 分钟前
XML 技术
开发语言
清晓粼溪4 分钟前
Java登录认证解决方案
java·开发语言
小徐Chao努力5 分钟前
Go语言核心知识点底层原理教程【变量、类型与常量】
开发语言·后端·golang
锥锋骚年6 分钟前
go语言异常处理方案
开发语言·后端·golang
沐知全栈开发6 分钟前
JSP 自动刷新技术详解
开发语言
特立独行的猫a8 分钟前
C++使用Boost的Asio库优雅实现定时器与线程池工具类
开发语言·c++·线程池·定时器·boost·asio
高洁0111 分钟前
DNN案例一步步构建深层神经网络(3)
python·深度学习·算法·机器学习·transformer
郝学胜-神的一滴12 分钟前
Linux C++ 守护进程开发指南
linux·运维·服务器·开发语言·c++·程序人生·性能优化
_dindong15 分钟前
笔试强训:Week -8
开发语言·c++·算法
AI_567816 分钟前
Jupyter交互式数据分析的效率革命
开发语言·python