免费公网动态IP方案

思路

方案说明
  • 电信公网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
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值