测试系统环境:CentOS 7.3
服务器A:1.1.1.1
服务器B:2.2.2.2
在服务器A和服务器B建立一个shell脚本,具体内容如下:
[root@1 ~]vim tunadd.sh #!/bin/bash modprobe ipip sip=${SIP} dip="" tun=${TUN:-tun} net=${NET:-172.16} mode="n" vp=0; ks=0; while getopts 's:d:t:n:x:v' opt ;do case $opt in x) mode="x";; s) sip="$OPTARG";; d) dip="$OPTARG";; t) tun="$OPTARG";; n) net="$OPTARG";; v) vp=1;; h) echo -e "Useage: $0 -s sourceip -d destionation ip -t tunnel name -n net pre" ;; *) echo "error";; esac done nset() { ip addr |grep eth |grep inet|awk '{print $2}' |grep "^172.*.*.*" >/dev/null 2>&1 && { v=`ip addr |grep eth |grep inet|awk '{print $2}'|awk -F'[/]' '{print $1}'` ;} net=${NET:-10.9}; [ -z "$v" ] || { nsip=$v ; ip t l |grep $nsip |grep $dip >/dev/null 2>&1 && exit 1 ; } [ $1 -eq 1 ] &&{ tun=${TUN:-tunn}; net=${NET:-10.10}; } } ip t l |grep $sip |grep $dip >/dev/null 2>&1 && exit 1; d=$(echo $dip|awk -F"." '{print $4}') ip t l |grep -v tunl0|awk '{print $1}' |sed 's/://g'|awk -F[_] '{print $3}' |grep $d >/dev/null 2>&1 && { tun=${TUN:-tunn} ; net=${NET:-172.18} ; ks=1; } [ $vp -eq 1 ] && { nset $ks $dip ;} [ $mode == "x" ]&&{ x=$sip;sip=$dip;dip=$x ;} [ "$sip" == "" ]&&{ echo "no sip" ;exit 1 ;} [ "$dip" == "" ]&&{ echo "no dip" ;exit 2 ;} s=$(echo $sip|awk -F"." '{print $4}') [ "$nsip" == "" ] ||{ sip=$nsip ;} [ $s -eq $d ]&&exit 3 ip t add ${tun}_${s}_$d mode ipip remote $dip local $sip ip l set ${tun}_${s}_$d up ip a add $net.$s.$d/32 peer $net.$d.$s dev ${tun}_${s}_$d
将shell脚本的权限设置为0755
[root@1 ~]#chmod 0755 tunadd.sh
在服务器B上执行脚本
[root@2 ~]./tunadd -s 2.2.2.2 -d 1.1.1.1
在服务器A上执行脚本,然后通过ip tun l 或者ifconfig tun_1_2 查看通道信息,ping服务B的通道IP,测试网络连通性
[root@1 ~]./tunadd -s 1.1.1.1 -d 2.2.2.2 [root@1 ~] [root@1 ~]# ip tun l tun_1_2: ip/ip remote 2.2.2.2 local 1.1.1.1 ttl inherit tunl0: ip/ip remote any local any ttl inherit nopmtudisc [root@1 ~]#ifconfig tun_1_2 tun_1_2: flags=209<UP,POINTOPOINT,RUNNING,NOARP> mtu 1480 inet 172.16.1.2 netmask 255.255.255.255 destination 172.16.2.1 tunnel txqueuelen 1 (IPIP Tunnel) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 [root@1 ~]# ping 172.16.2.1 PING 172.16.1.2 (172.16.2.1) 56(84) bytes of data. 64 bytes from 172.16.2.1: icmp_seq=1 ttl=64 time=0.021 ms 64 bytes from 172.16.2.1: icmp_seq=2 ttl=64 time=0.044 ms 64 bytes from 172.16.2.1: icmp_seq=3 ttl=64 time=0.043 ms ^C --- 172.16.2.1 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 1999ms rtt min/avg/max/mdev = 0.021/0.036/0.044/0.010 ms [root@1 ~]#
到此我们的IPIP通道就建立完成了