讓花成花 讓我成我

自动关机脚本

#!/bin/bash

# 定义需要Ping的地址
ADDRESSES=("8.8.8.8" "1.1.1.1" "example.com")

# 检查是否存在5分钟后关机的计划
check_shutdown_plan() {
    shutdown_task_id=$(atq | awk '{print $1}')
    
    for id in $shutdown_task_id; do
        task_info=$(at -c $id 2>/dev/null)
        if echo "$task_info" | grep -q "shutdown -h now"; then
            echo "$id"
            return
        fi
    done
    echo ""
}

# 初始化ping结果数组
declare -A PING_RESULTS

# 执行ping并将结果存入数组
for address in "${ADDRESSES[@]}"; do
    if ping -c 1 "$address" > /dev/null 2>&1; then
        PING_RESULTS["$address"]=0  # 0表示成功
    else
        PING_RESULTS["$address"]=1  # 1表示超时
    fi
done

# 检查所有地址是否都超时
all_timeout=true

for result in "${PING_RESULTS[@]}"; do
    if [ "$result" -eq 0 ]; then
        all_timeout=false
        break
    fi
done

# 检查计划任务
shutdown_id=$(check_shutdown_plan)

if $all_timeout; then
    if [ -z "$shutdown_id" ]; then
        # 创建5分钟后关机的计划
        echo "shutdown -h now" | at now + 5 minutes
        echo "All addresses timed out. Shutdown plan created."
    else
        echo "All addresses timed out. Shutdown plan already exists."
    fi
else
    if [ -n "$shutdown_id" ]; then
        # 取消5分钟后关机的计划
        atrm "$shutdown_id"
        echo "Addresses responded. Shutdown plan cancelled."
    else
        echo "Addresses responded. No shutdown plan to cancel."
    fi
fi
#!/bin/bash

# 定义需要Ping的地址
ADDRESSES=("8.8.8.8" "1.1.1.1" "example.com")

# 定义标志文件路径
FLAG_FILE="/tmp/ping_timeout_flag"

# 执行ping并将结果存入数组
declare -A PING_RESULTS

for address in "${ADDRESSES[@]}"; do
    if ping -c 1 "$address" > /dev/null 2>&1; then
        PING_RESULTS["$address"]=0  # 0表示成功
    else
        PING_RESULTS["$address"]=1  # 1表示超时
    fi
done

# 检查所有地址是否都超时
all_timeout=true

for result in "${PING_RESULTS[@]}"; do
    if [ "$result" -eq 0 ]; then
        all_timeout=false
        break
    fi
done

if $all_timeout; then
    # 当所有地址都超时时,检查标志文件是否存在
    if [ ! -f "$FLAG_FILE" ]; then
        # 创建标志文件
        touch "$FLAG_FILE"
        echo "All addresses timed out. Flag file created."
    else
        echo "All addresses timed out. Flag file already exists."
    fi
else
    # 当不再全部超时时,检查标志文件
    if [ -f "$FLAG_FILE" ]; then
        # 执行etherwake命令
        etherwake <MAC_ADDRESS>  # 请替换 <MAC_ADDRESS> 为实际的MAC地址

        # 删除标志文件
        rm "$FLAG_FILE"
        echo "Addresses responded. Etherwake executed and flag file removed."
    else
        echo "Addresses responded. No flag file found."
    fi
fi
自动关机脚本

https://llb.im/posts/28.html

作者

Qin

发布时间

2024-09-02

许可协议

CC BY 4.0

添加新评论