我有分寸

一个自动搭建ipip隧道的脚本

gnawux ipiplinuxroutescriptstunnel

场景是这样的,两台机器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

之后判断一下连在缺省接口上的IP地址
local_ip=$(ifconfig $default_dev | grep "inet addr"|sed -ne 's/.*inet addr:\([.0-9]\+\).*/\1/p')

然后在远程主机上启动隧道、配置路由,并设置NAT:
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 machine
iptunnel 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 rule
if [ "${flag_nogw}" = "false" ]
then
        route add -net ${tnet_cidr} gw ${default_gw}
        route del default gw ${default_gw}
else
        route add -net ${tnet_cidr} dev ${default_dev}
        route del default dev ${default_dev}
fi
route add default gw ${remote_tun_addr}

完毕。
gnawux
me!#$!@#$@#$wangxu!@#$%^&*()_me