思路
方案说明
- 电信公网ip变化
- 电信提供了公网ip,但是由于光猫会定期重启(目前看应该是光猫的设置,从光猫的日志能看到3天左右重启,但是重启的原因未知),导致外网ip在不停变化
- 方案组成
- 同步服务
- 对于家庭网络它有外网,对于公司网络也有外网,通过一个和ip解耦的分布式存储(git)实现动态ip同步
- 外网ip获取
- 通过curl -L ip.tool.lu可以获取动态ip
- 定时任务
- 当时上传任务,获取动态ip,并更新到同步服务中
- 定时同步任务,从同步服务中获取最新ip,更新
- 本地dns服务/etc/hosts
- 同步服务
优缺点
- 优点
- 免费,不要钱,哈哈
- 缺点
- 暂时没想到吧,也谈不上缺点
实现
同步服务
通过gitee创建一个项目,创建dynamic-ip文件,并配置免密
git config credential.helper store
定时同步任务
#!/bin/bash -x
# author hehuang 20210926
# 这个脚本用来实现动态ip拉取
# 从git上拉取最新的ip信息,如果ip发生变化,则更新/etc/hosts
# 要求git已支持无密pull:git config credential.helper store
# 注意这个脚本必须以root执行,因为需要更新/etc/hosts
# param1 动态ip文件
#
# 通过sed c命令进行替换,注意不能-n,会导致信息丢失
function updateIP() {
new=$1
sed -i /myhome$/c"${new} myhome" /etc/hosts
}
if [ $# -le 0 ];then
echo "必须指定动态ip文件"
exit 1
fi
dynamic_ip=$1
if [ ! -r $dynamic_ip ]; then
echo "动态ip文件不存在"
exit 1
fi
git_path=${dynamic_ip%/*}
git_file=${dynamic_ip##*/}
cd $git_path
git pull
# $()支持$
new_ip=$(cat $git_file|tr -d '\r\n')
old_ip=$(sed -n /myhome$/p /etc/hosts|awk '{print $1}')
now=`date +'%Y-%m-%d %H:%M:%S'`
echo "${now}: new-[${new_ip}], old-[${old_ip}]"
# 更新/etc/hosts
if [ $new_ip != $old_ip ];then
updateIP $new_ip
echo "update ip success!"
else
echo "ip未发生变化"
fi
定时上传任务
#!/bin/bash -x
# author hehuang 20210926
# 这个脚本用于上传同步动态ip,从工具网站ip.tool.lu获取最新的动态ip,如果ip地址发生变化,则通过到git上
# 要求1,git文件必须支持无密push/pull:git config credential.helper store
# param1 动态ip地址文件
function uploadIP() {
git_file=$2
current=$1
echo $current > $git_file
git add -A
now=`date +'%Y-%m-%d %H:%M:%S'`
git commit -m "$now"
git push
}
if [ $# -le 0 ];then
echo "必须指定动态ip文件"
exit 1
fi
dynamic_ip=$1
if [ ! -r $dynamic_ip ];then
echo "动态ip文件不存在"
exit 1
fi
git_path=${dynamic_ip%/*}
git_file=${dynamic_ip##*/}
cd $git_path
git pull
current=$(curl -L -s ip.tool.lu |grep IP |awk '{print $2}'|tr -d '\n\r')
old=$(cat $git_file | tr -d '\r\n')
now=`date +'%Y-%m-%d %H:%M:%S'`
echo "${now}: new-[${current}], old-[${old}]"
if [ $current != $old ];then
uploadIP $current $git_file
echo "upload ip success!"
else
echo "ip 未发生变化"
fi
crontab配置
在root用户下执行crontab -e添加,注意保证crontab服务是正常的
0 8 * * * /home/hehuang/git/code/bash/ip-sync.sh /home/hehuang/git/ip-sync/dynamic-ip
0 6 * * * /home/hehuang/git/code/bash/ip-upload.sh /home/hehuang/git/ip-sync/dynamic-ip