Created
September 18, 2025 06:03
-
-
Save esmaeelE/6541139e075e36e019ca6987c6c8e9a2 to your computer and use it in GitHub Desktop.
gre_tunnel.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# grab from [Understanding GRE tunnels using Linux network namespaces](https://routemyip.com/posts/linux/networking/gre-tunnels/) | |
# great article by Sarath Chandra Mekala. | |
# Enable gre kernel module | |
modprobe ip_gre | |
# Create the network namespaces | |
ip netns add host1 | |
ip netns add host2 | |
ip netns add internet | |
# Create the topology and connection between them | |
ip link add veth0 type veth peer name veth1 | |
ip link add veth2 type veth peer name veth3 | |
ip link set veth0 netns host1 | |
ip link set veth1 netns internet | |
ip link set veth2 netns internet | |
ip link set veth3 netns host2 | |
# host1 namespace settings | |
ip netns exec host1 ip addr add 172.16.10.2/24 dev veth0 | |
ip netns exec host1 ip link set veth0 up | |
ip netns exec host1 ip link set lo up | |
# add default route for host1 namespace | |
ip netns exec host1 ip route add default via 172.16.10.1 | |
# host2 namespace settings | |
ip netns exec host2 ip addr add 152.16.10.2/24 dev veth3 | |
ip netns exec host2 ip link set veth3 up | |
ip netns exec host2 ip link set lo up | |
# add default route for host2 namespace | |
ip netns exec host2 ip route add default via 152.16.10.1 | |
# internet namesapce settings | |
ip netns exec internet ip addr add 172.16.10.1/24 dev veth1 | |
ip netns exec internet ip link set veth1 up | |
ip netns exec internet ip addr add 152.16.10.1/24 dev veth2 | |
ip netns exec internet ip link set veth2 up | |
ip netns exec internet ip link set lo up | |
# enable routing on this namespace | |
ip netns exec internet sysctl -w net.ipv4.ip_forward=1 | |
# Create gre tunnel on host1 | |
ip netns exec host1 ip tunnel add tun0 mode gre remote 152.16.10.2 local 172.16.10.2 ttl 255 | |
# set IP and start interface | |
ip netns exec host1 ip addr add 192.168.50.1/30 dev tun0 | |
ip netns exec host1 ip link set tun0 up | |
# Create gre tunnel on host2 | |
ip netns exec host2 ip tunnel add tun0 mode gre local 152.16.10.2 remote 172.16.10.2 ttl 255 | |
# set IP and start interface | |
ip netns exec host2 ip addr add 192.168.50.2/30 dev tun0 | |
ip netns exec host2 ip link set tun0 up | |
echo "Setup GRE tunnel done." | |
# Check connection # | |
########################################## | |
## ip netns exec host1 hostname -I | |
## ip netns exec host1 ping 192.168.50.2 | |
## ip netns exec host2 ping hostname -I | |
## ip netns exec host2 ping 192.168.50.1 | |
########################################## |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment