一个自动搭建ipip隧道的脚本
场景是这样的,两台机器A和B,通过缺省路由互相可达;希望A通过B的连接出去;A的地址为动态分配,且A可能的interface不缺定,因此,上来先给点先决条件:
#!/bin/bash
default_dev="wlan0"
default_gw="192.168.12.1"
flag_nogw="false"
local_ip=192.168.12.111
thost_ip=192.168.32.214
tnet_cidr="192.168.32.0/21"
local_tun_addr="172.16.1.1"
remote_tun_addr="172.16.1.254"
tun_dev="tun9"
tun_cidr="172.16.0.0/16"
然后,想办法获取缺省路由的接口和网关地址,当然,不一定所有的缺省路由都有网关地址
# get default gw and local ip address
route -n | while read dst gw msk flag metric ref use iface
do
if [ "$dst" = "0.0.0.0" -a "$msk" = "0.0.0.0" ]
then
default_dev=$iface
if [ "$flag" = "UG" ]
then
default_gw=$gw
else
flag_nogw="true"
fi
fi
done
local_ip=$(ifconfig $default_dev | grep "inet addr"|sed -ne 's/.*inet addr:\([.0-9]\+\).*/\1/p')
ssh ${thost_ip} iptunnel add ${tun_dev} mode ipip remote $local_ip local ${thost_ip}ssh ${thost_ip} ifconfig ${tun_dev} ${remote_tun_addr}ssh ${thost_ip} route add -net ${tun_cidr} dev ${tun_dev}ssh ${thost_ip} iptables -t nat -A POSTROUTING -s ${local_tun_addr} -j MASQUERADE
#setup tunnel on local machineiptunnel add ${tun_dev} mode ipip remote ${thost_ip} local ${local_ip}ifconfig ${tun_dev} ${local_tun_addr}route add -net ${tun_cidr} dev ${tun_dev}
#setup default route ruleif [ "${flag_nogw}" = "false" ]thenroute add -net ${tnet_cidr} gw ${default_gw}route del default gw ${default_gw}elseroute add -net ${tnet_cidr} dev ${default_dev}route del default dev ${default_dev}firoute add default gw ${remote_tun_addr}