如何写一个脚本智能关机

wen 实用脚本 3

本文目录导读:

如何写一个脚本智能关机

  1. 基础版:定时关机(Windows批处理)
  2. 智能空闲检测(Python版)
  3. 条件触发版(根据特定条件关机)
  4. 使用说明
  5. 安装依赖
  6. 高级功能建议

我来为你提供几种智能关机脚本的写法,从简单到高级,你可以根据需求选择:

基础版:定时关机(Windows批处理)

@echo off
:: 定时关机脚本
echo ========================================
echo        智能关机工具
echo ========================================
echo.
echo 请选择操作:
echo [1] 30分钟后关机
echo [2] 1小时后关机
echo [3] 2小时后关机
echo [4] 取消定时关机
echo [5] 立即关机
echo.
set /p choice=请输入选项(1-5): 
if "%choice%"=="1" (
    shutdown /s /t 1800 /c "系统将在30分钟后自动关机,请保存工作!"
    echo 已设置30分钟后关机
) else if "%choice%"=="2" (
    shutdown /s /t 3600 /c "系统将在1小时后自动关机,请保存工作!"
    echo 已设置1小时后关机
) else if "%choice%"=="3" (
    shutdown /s /t 7200 /c "系统将在2小时后自动关机,请保存工作!"
    echo 已设置2小时后关机
) else if "%choice%"=="4" (
    shutdown /a
    echo 已取消定时关机
) else if "%choice%"=="5" (
    shutdown /s /t 0
    echo 系统即将关机
) else (
    echo 无效选项!
)
pause

智能空闲检测(Python版)

这个脚本会在系统空闲指定时间后自动关机:

import psutil
import time
import os
import sys
from datetime import datetime
class SmartShutdown:
    def __init__(self, idle_threshold=30, check_interval=5):
        self.idle_threshold = idle_threshold  # 空闲阈值(分钟)
        self.check_interval = check_interval  # 检查间隔(秒)
        self.last_active_time = time.time()
    def get_system_activity(self):
        """获取系统活动状态"""
        # 获取CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        # 获取网络活动
        net_io = psutil.net_io_counters()
        bytes_sent = net_io.bytes_sent
        bytes_recv = net_io.bytes_recv
        # 获取磁盘活动
        disk_io = psutil.disk_io_counters()
        read_bytes = disk_io.read_bytes
        write_bytes = disk_io.write_bytes
        return {
            'cpu_percent': cpu_percent,
            'network_active': bytes_sent + bytes_recv,
            'disk_active': read_bytes + write_bytes
        }
    def is_system_idle(self):
        """判断系统是否空闲"""
        activity = self.get_system_activity()
        # 检查CPU使用率
        if activity['cpu_percent'] > 10:
            return False
        # 检查是否有明显网络或磁盘活动
        if activity['network_active'] > 1000 or activity['disk_active'] > 1000:
            return False
        return True
    def run(self):
        """主运行循环"""
        print(f"智能关机脚本已启动")
        print(f"空闲 {self.idle_threshold} 分钟后将自动关机")
        print("按 Ctrl+C 退出")
        print("-" * 50)
        try:
            while True:
                if self.is_system_idle():
                    idle_duration = (time.time() - self.last_active_time) / 60
                    if idle_duration >= self.idle_threshold:
                        print(f"\n[{datetime.now().strftime('%H:%M:%S')}]")
                        print(f"系统已空闲 {idle_duration:.1f} 分钟,准备关机...")
                        self.shutdown()
                        break
                    else:
                        remaining = self.idle_threshold - idle_duration
                        print(f"系统空闲中... {remaining:.1f} 分钟后关机 (Ctrl+C取消)")
                else:
                    self.last_active_time = time.time()
                    print("系统活动进行中,重置计时器")
                time.sleep(self.check_interval)
        except KeyboardInterrupt:
            print("\n脚本已手动终止")
    def shutdown(self):
        """执行关机操作"""
        print("正在执行关机...")
        if os.name == 'nt':  # Windows
            os.system("shutdown /s /f /t 0")
        else:  # Linux/Mac
            os.system("sudo shutdown -h now")
if __name__ == "__main__":
    # 配置参数
    IDLE_THRESHOLD = 15  # 空闲15分钟后关机
    CHECK_INTERVAL = 10   # 每10秒检查一次
    # 创建并运行智能关机脚本
    smart_shutdown = SmartShutdown(IDLE_THRESHOLD, CHECK_INTERVAL)
    smart_shutdown.run()

条件触发版(根据特定条件关机)

import psutil
import time
import os
from datetime import datetime
class ConditionalShutdown:
    def __init__(self):
        self.conditions = {
            'cpu_temp_threshold': 85,  # CPU温度阈值(摄氏度)
            'battery_low_threshold': 20,  # 电池低电量阈值(%)
            'download_complete': False,  # 下载完成检测
        }
    def check_cpu_temperature(self):
        """检查CPU温度"""
        try:
            temps = psutil.sensors_temperatures()
            if 'coretemp' in temps:
                cpu_temp = max(temp.current for temp in temps['coretemp'])
                return cpu_temp, cpu_temp > self.conditions['cpu_temp_threshold']
        except:
            pass
        return None, False
    def check_battery(self):
        """检查电池状态"""
        battery = psutil.sensors_battery()
        if battery:
            percent = battery.percent
            is_charging = battery.power_plugged
            return percent, is_charging, percent < self.conditions['battery_low_threshold']
        return None, None, False
    def check_disk_space(self, threshold=5):
        """检查磁盘空间(GB)"""
        disk_usage = psutil.disk_usage('/')
        free_gb = disk_usage.free / (1024**3)
        return free_gb, free_gb < threshold
    def monitor_and_shutdown(self):
        """监控并执行关机"""
        print("条件触发关机监控已启动")
        print("-" * 50)
        while True:
            # 检查CPU温度
            cpu_temp, is_overheated = self.check_cpu_temperature()
            if is_overheated and cpu_temp:
                print(f"[{datetime.now().strftime('%H:%M:%S')}] CPU温度过高: {cpu_temp}°C")
                self.shutdown("CPU温度过高")
                break
            # 检查电池状态
            battery_percent, is_charging, is_low = self.check_battery()
            if is_low and not is_charging and battery_percent:
                print(f"[{datetime.now().strftime('%H:%M:%S')}] 电池电量不足: {battery_percent}%")
                self.shutdown("电池电量不足")
                break
            # 检查磁盘空间
            free_space, is_low_disk = self.check_disk_space()
            if is_low_disk:
                print(f"[{datetime.now().strftime('%H:%M:%S')}] 磁盘空间不足: {free_space:.1f}GB")
                self.shutdown("磁盘空间不足")
                break
            print(f"[{datetime.now().strftime('%H:%M:%S')}] 系统状态正常")
            time.sleep(30)  # 每30秒检查一次
    def shutdown(self, reason):
        """执行关机"""
        print(f"关机原因: {reason}")
        print("5秒后执行关机...")
        time.sleep(5)
        if os.name == 'nt':  # Windows
            os.system(f"shutdown /s /f /t 0 /c \"{reason}\"")
        else:
            os.system("sudo shutdown -h now")
if __name__ == "__main__":
    conditional_shutdown = ConditionalShutdown()
    conditional_shutdown.monitor_and_shutdown()

使用说明

Windows系统:

:: 在需要时执行:直接双击批处理文件或通过命令提示符运行
:: 注意:某些情况下需要管理员权限

Linux系统:

# 添加执行权限
chmod +x smart_shutdown.py
# 运行脚本
python3 smart_shutdown.py

安装依赖

# Python环境需要安装psutil库
pip install psutil

高级功能建议

如果你需要更多功能,可以考虑:

  1. GUI界面:用tkinter或PyQt开发图形界面
  2. 远程控制:通过Web界面或手机APP控制
  3. 计划任务:集成到系统计划任务中
  4. 日志记录:记录关机历史
  5. 白名单程序:特定程序运行时延迟关机

选择哪种方案取决于你的具体需求,最简单的是直接用系统命令,最智能的是Python脚本方案,需要我解释某个特定部分吗?

抱歉,评论功能暂时关闭!