编写一个脚本监控当前的公网 IPv4 和 IPv6 地址,并定时通过 Telegram Bot 发送 IP 信息,可以通过 curl 获取公网 IP,并利用 cron 来定时执行脚本。

创建脚本

sudo nano ip_notifier.sh

将以下内容复制到脚本中:

#!/bin/bash

# Telegram Bot API Token 和 Chat ID
BOT_TOKEN="your_bot_token_here"
CHAT_ID="your_chat_id_here"

# 获取公网 IPv4 和 IPv6
IPV4=$(curl -4 -s https://ifconfig.co)
IPV6=$(curl -6 -s https://ifconfig.co)

# 组装要发送的消息
MESSAGE="Public IP update for $(hostname):%0AIPv4: ${IPV4:-Unavailable}%0AIPv6: ${IPV6:-Unavailable}"

# 发送到 Telegram
curl -s --data "chat_id=$CHAT_ID&text=$MESSAGE" "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" > /dev/null

赋予脚本执行权限

sudo chmod +x ip_notifier.sh

添加 cron 任务

sudo crontab -e

在 crontab 文件中添加以下行:

0 * * * * /usr/local/bin/ip_notifier.sh

这条 cron 任务将会每小时执行一次 ip_notifier.sh 脚本。

测试

./ip_notifier.sh
Last modification:September 13th, 2024 at 08:16 am