0%

检查断网重启Mac

反馈请联系hertz@hertzwang.com,谢谢

用Python脚本来检查Mac联网状态,在达到条件后重启Mac

Python 脚本

# -*- coding: utf-8 -*-
import os
import asyncio
import time
from enum import Enum

# 策略enum:1-重启电脑 2-启动网卡
class RunActionType(Enum):
    reboot = 1
    restart_net = 2
    

# root密码
root_pwd = ''
# 策略
run_action_type = RunActionType.restart_net.value

# 退出循环标记
allow_loop = True
# 时间间隔
tiem_sleep_interval = 3
# 失败次数
failed_count = 0
# 失败最大次数
failed_max_count = 2
# 终端命令
command_reboot = 'echo %s | sudo -S reboot' % root_pwd
command_network_down = 'echo %s | sudo -S ifconfig en0 down' % root_pwd
command_network_up = 'echo %s | sudo -S ifconfig en0 up' % root_pwd


# 检查网络状态
async def loop_ping():
    global allow_loop, failed_count
    
    while allow_loop:
        result = os.system('curl baidu.com')
        if result:
            failed_count += 1
            print(result)
        else:
            failed_count = 0
            
        if failed_count >= failed_max_count:
            allow_loop = False
            failed_count = 0
            run_action()
        else:
            time.sleep(tiem_sleep_interval)
        

# 策略
def run_action():
    if run_action_type == RunActionType.reboot.value:
        reboot_action()
    elif run_action_type == RunActionType.restart_net.value:
        restart_net_action()

# 启动电脑
def reboot_action():
    print("启动电脑")
    os.system(command_reboot)
    
# 启动网卡
def restart_net_action():
    print("重启网卡")
    os.system(command_network_down)
    time.sleep(5)
    os.system(command_network_up)
    print("网卡重启结束")

if __name__ == '__main__':
    print("开始监听网络连接")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(loop_ping())

部署

  1. 将整个文件夹放到当前用户目录下,即cd ~目录下
  2. 制作启动程序,参考链接https://jingyan.baidu.com/article/9c69d48fe7a2c913c9024eb6.html
    1. 打开 自动操作.app->新建文稿->应用程序->选取,或者文件->新建->应用程序->选取
    2. 搜索shell,将运行Shell脚本拖动到右边的
    3. 运行Shell脚本的Shell路径选择/bin/bash
    4. 内容输入 pythonBinPath pyFilePath,例如:/usr/bin/python3 ~/Script/reboot.py
      • pythonBinPath:python命令路径,终端执行which python查看
      • pyFilePath:python脚本路径
    5. 执行文件->存储保存应用程序
  3. 添加启动项
    1. 打开系统偏好设置->用户与群组
    2. 选择当前用户->登录项-> + ,选择制作的启动程序
  4. 配置参数
    1. 打开reboot.py
    2. 修改root_pwd
    3. 修改run_action_type
    4. 修改其它参数
  5. 双击制作的启动程序,启动成功后会在Mac上的菜单栏中显示图标(旋转的⚙️)