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
相关推荐
zhangyao9403301 小时前
关于js导入Excel时,Excel的(年/月/日)日期是五位数字的问题。以及对Excel日期存在的错误的分析和处理。
开发语言·javascript·excel
闲人编程1 小时前
Python在网络安全中的应用:编写一个简单的端口扫描器
网络·python·web安全·硬件·端口·codecapsule·扫描器
骑驴看星星a1 小时前
【Three.js--manual script】4.光照
android·开发语言·javascript
星释2 小时前
Rust 练习册 :Leap与日期计算
开发语言·后端·rust
悟能不能悟4 小时前
java的java.sql.Date和java.util.Date的区别,应该怎么使用
java·开发语言
Mr_Xuhhh4 小时前
GUI自动化测试--自动化测试的意义和应用场景
python·集成测试
2301_764441334 小时前
水星热演化核幔耦合数值模拟
python·算法·数学建模
循环过三天4 小时前
3.4、Python-集合
开发语言·笔记·python·学习·算法
Q_Q5110082855 小时前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php
_院长大人_6 小时前
设计模式-工厂模式
java·开发语言·设计模式