收起左侧

非直连UPS飞牛断 电关机脚本

5
回复
942
查看
[ 复制链接 ]

2

主题

3

回帖

0

牛值

江湖小虾

2025-1-22 14:32:51 显示全部楼层 阅读模式

[i=s] 本帖最后由 ㅤㅤㅤ_Duwe2 于 2025-1-22 20:32 编辑 [/i]<br /> <br />

[i=s] 本帖最后由 ㅤㅤㅤ_Duwe2 于 2025-1-22 20:31 编辑 [/i]

[i=s] 本帖最后由 ㅤㅤㅤ_Duwe2 于 2025-1-22 20:28 编辑 [/i]

[i=s] 本帖最后由 ㅤㅤㅤ_Duwe2 于 2025-1-22 14:35 编辑 [/i]

背景:

家里威联通、群晖、飞牛都在用,UPS共用山克的,威联通直连UPS,群晖和飞牛使用脚本检测威联通是否关机,设置定时任务1分钟执行1次,累计10次ping不通威联通,执行关机操作。

代码里面的**是g _ m 中间没空格

脚本内容:


import subprocess
import os
import json
import atexit
import logging
import platform

# 配置日志记录
logging.basicConfig(filename='/vol1/1000/app/pin**onitor/logs/pin**onitor.log', level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

def ping_ip(ip):
    """
    尝试ping指定的IP地址,返回ping的结果(成功或失败)。
    """
    try:
        if platform.system() == 'Windows':
            result = subprocess.run(['ping', '-n', '2', ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        else:
            result = subprocess.run(['ping', '-c', '2', ip], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        if result.returncode == 0:
            return True
        else:
            return False
    except Exception as e:
        logging.error(f"Error occurred while pinging {ip}: {e}")
        return False

def save_failure_count(failure_count):
    """
    将失败次数保存到JSON文件中。
    """
    try:
        with open('ping_failure_count.json', 'w') as f:
            json.dump({'count': failure_count}, f)
    except Exception as e:
        logging.error(f"Error occurred while saving failure count: {e}")

def load_failure_count():
    """
    从JSON文件中加载失败次数。
    """
    try:
        with open('ping_failure_count.json', 'r') as f:
            data = json.load(f)
            return data.get('count', 0)
    except FileNotFoundError:
        return 0
    except Exception as e:
        logging.error(f"Error occurred while loading failure count: {e}")
        return 0

def shutdown_system():
    """
    根据当前操作系统类型执行关机命令。
    """
    if platform.system() == 'Windows':
        os.system('shutdown /s /t 0')
    else:
        os.system('shutdown -h now')

if __name__ == "__main__":
    target_ip = '10.77.19.6'  # 请替换为你要ping的IP
    failure_count = load_failure_count()
    if not ping_ip(target_ip):
        failure_count += 1
    else:
        failure_count = 0
    if failure_count >= 10:
        logging.error(f"Failed to ping {target_ip} for 10 consecutive times. Shutting down the system...")
        shutdown_system()
    else:
        logging.info(f"Ping result: {'success' if failure_count == 0 else 'failure'}, current failure count: {failure_count}")
    atexit.register(save_failure_count, failure_count)

"""
mkdir /vol1/1000/app/pin**onitor/
mkdir /vol1/1000/app/pin**onitor/logs
cd /vol1/1000/app/pin**onitor/logs
chmod +x pin**onitor.py
crontab -e
* * * * * /usr/bin/python3 /vol1/1000/app/pin**onitor/pin**onitor.py
"""
收藏
送赞 2
分享

2

主题

3

回帖

0

牛值

江湖小虾

2025-1-22 14:34:38 楼主 显示全部楼层
windows平台下也可以用,设置定时任务即可

0

主题

7

回帖

0

牛值

江湖小虾

2025-3-29 21:56:10 显示全部楼层
logging.info(f"ing这里缺代码,被系统自动变成表情了。。。

0

主题

7

回帖

0

牛值

江湖小虾

2025-3-29 22:11:36 显示全部楼层
#!/bin/bash

# 配置参数
ROUTER_IP="192.168.1.1"          # 路由器IP地址
CHECK_INTERVAL=5                  # 检测间隔(秒)
FAIL_THRESHOLD=3                  # 连续失败次数阈值
SHUTDOWN_DELAY=$((45*60))        # 关机延迟(45分钟)
PING_TIMEOUT=2                    # Ping超时时间(秒)

# 初始化计数器
fail_count=0

while true; do
    if ping -c 1 -W $PING_TIMEOUT $ROUTER_IP &> /dev/null; then
        fail_count=0
    else
        ((fail_count++))

        if [ $fail_count -ge $FAIL_THRESHOLD ]; then
            echo "[$(date +'%F %T')] 检测到停电,将在45分钟后关机..."

            # 倒计时和恢复检测
            remaining=$SHUTDOWN_DELAY
            shutdown_aborted=false

            while [ $remaining -gt 0 ]; do
                sleep 10
                remaining=$((remaining-10))

                # 持续检测网络恢复
                if ping -c 1 -W $PING_TIMEOUT $ROUTER_IP &> /dev/null; then
                    echo "[$(date +'%F %T')] 网络恢复,取消关机!"
                    shutdown_aborted=true
                    break
                fi
            done

            if ! $shutdown_aborted; then
                echo "[$(date +'%F %T')] 执行关机操作..."
                shutdown -h now
                exit 0
            fi

            # 重置状态继续监控
            fail_count=0
        fi
    fi
    sleep $CHECK_INTERVAL
done
我自己弄了个正在测试  详情 回复
2025-3-29 22:12

0

主题

7

回帖

0

牛值

江湖小虾

2025-3-29 22:12:11 显示全部楼层

我自己弄了个正在测试
测试好了么 我找过了几个脚本都不行  详情 回复
2025-4-11 18:36

0

主题

4

回帖

0

牛值

江湖小虾

2025-4-11 18:36:08 显示全部楼层
东东的星空 发表于 2025-3-29 22:12
我自己弄了个正在测试

测试好了么 我找过了几个脚本都不行
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则