以下是一个支持Windows和Linux系统的Python定时关机脚本,允许设置定时关机或取消关机计划:
python">import sys
import os
import datetime
import ctypes
import redef is_admin():"""检查是否具有管理员权限"""if os.name == 'nt':try:return ctypes.windll.shell32.IsUserAnAdmin()except:return Falseelse:return os.geteuid() == 0def parse_time_argument(arg):"""解析时间参数为秒数"""# 尝试解析绝对时间 HH:MMtry:time_obj = datetime.datetime.strptime(arg, "%H:%M").time()now = datetime.datetime.now()target = datetime.datetime.combine(now.date(), time_obj)if target < now:target += datetime.timedelta(days=1)delta = target - nowreturn int(delta.total_seconds())except ValueError:pass# 处理相对时间if arg.startswith('+'):rel_time = arg[1:]# 尝试解析为分钟数try:minutes = int(rel_time)return minutes * 60except ValueError:pass# 处理带h和m的情况match = re.match(r'^(?:(\d+)h)?(?:(\d+)m)?$', rel_time)if match:hours = int(match.group(1) or 0)minutes = int(match.group(2) or 0)return (hours * 3600) + (minutes * 60)else:raise ValueError(f"无效的时间格式: {arg}")elif arg.lower() == 'now':return 0else:raise ValueError(f"无法解析的时间参数: {arg}")def main():# 系统兼容性检查if os.name not in ('nt', 'posix'):print("此脚本仅支持Windows和Linux系统。")sys.exit(1)# 权限检查if not is_admin():print("请以管理员/root权限运行此脚本。")sys.exit(1)# 参数验证if len(sys.argv) != 2:print("用法: python shutdown_timer.py [时间|cancel]")print("时间格式:")print(" HH:MM 绝对时间(如 22:00)")print(" +数字 相对分钟(如 +60 表示60分钟后)")print(" +NhNm 复合时间(如 +1h30m 表示1.5小时后)")print(" now 立即关机")print(" cancel 取消关机计划")sys.exit(1)arg = sys.argv[1]# 取消关机逻辑if arg.lower() == 'cancel':if os.name == 'nt':os.system("shutdown /a")else:os.system("shutdown -c")print("关机计划已取消。")return# 解析时间并执行关机try:seconds = parse_time_argument(arg)if seconds < 0:print("错误:时间参数无效。")sys.exit(1)# 计算关机时间shutdown_time = datetime.datetime.now() + datetime.timedelta(seconds=seconds)# 执行系统命令if os.name == 'nt':os.system(f"shutdown /s /t {seconds}")else:minutes = max(seconds // 60, 1) # Linux至少需要1分钟os.system(f"shutdown -h +{minutes}")print(f"系统将在 {shutdown_time.strftime('%Y-%m-%d %H:%M:%S')} 关机")except ValueError as e:print(f"参数错误: {e}")sys.exit(1)if __name__ == "__main__":main()
使用方法:
-
设置定时关机:
# Windows(管理员权限) python shutdown_timer.py 22:00 # 今晚22点关机 python shutdown_timer.py +60 # 60分钟后关机 python shutdown_timer.py +1h30m # 1小时30分钟后关机 python shutdown_timer.py now # 立即关机# Linux(root权限) sudo python3 shutdown_timer.py 22:00 sudo python3 shutdown_timer.py +120
-
取消关机计划:
# Windows python shutdown_timer.py cancel# Linux sudo python3 shutdown_timer.py cancel
功能说明:
- 支持Windows和Linux系统
- 支持绝对时间(HH:MM格式)和相对时间(+分钟数/+NhNm格式)
- 自动处理跨天的时间计算
- 需要管理员/root权限运行
- 提供清晰的错误提示和帮助信息
注意事项:
- Windows系统需要以管理员身份运行命令提示符/PowerShell
- Linux系统需要使用sudo获取root权限
- 立即关机操作无法撤销,请谨慎使用
- 时间参数区分大小写(now/cancel为小写)