Skip to content

Instantly share code, notes, and snippets.

@Nexarian
Created January 4, 2025 06:13
Show Gist options
  • Save Nexarian/ab2ff893e1d699d9cd24e501e07cd805 to your computer and use it in GitHub Desktop.
Save Nexarian/ab2ff893e1d699d9cd24e501e07cd805 to your computer and use it in GitHub Desktop.
IP Routing with Namespaces
#!/usr/bin/env bash
set -ex
BRIDGE_NAME="br0"
BRIDGE_IP="192.168.92.1"
setup_bridge() {
echo "Setting up bridge $BRIDGE_NAME"
ip link add name $BRIDGE_NAME type bridge
ip addr add $BRIDGE_IP/24 dev $BRIDGE_NAME
ip link set $BRIDGE_NAME up
}
create_namespace() {
local ns_name=$1
local veth=$2
local br_veth=$3
local ip_addr=$4
local table_id=$5
local external_gateway=$6
echo "Creating namespace: $ns_name"
ip netns add "$ns_name"
echo "Setting up veth pair: $veth <-> $br_veth"
ip link add "$veth" type veth peer name "$br_veth"
ip link set "$veth" netns "$ns_name"
ip link set "$br_veth" master $BRIDGE_NAME
echo "Configuring namespace $ns_name with IP: $ip_addr"
ip netns exec "$ns_name" ip addr add "$ip_addr/24" dev "$veth"
ip netns exec "$ns_name" ip link set "$veth" up
ip netns exec "$ns_name" ip link set lo up
ip link set "$br_veth" up
echo "Setting up routing for $ns_name"
ip netns exec "$ns_name" ip route add default via $BRIDGE_IP dev "$veth"
# Add the specific route on the host
ip route add 192.168.91.0/24 via "$external_gateway" dev eth0 table "$table_id"
ip rule add from "$ip_addr" table "$table_id"
echo "Namespace $ns_name configured successfully!"
}
enable_nat() {
echo "Enabling NAT"
iptables -t nat -A POSTROUTING -s 192.168.92.0/24 -o eth0 -j MASQUERADE
iptables -A FORWARD -i $BRIDGE_NAME -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o $BRIDGE_NAME -j ACCEPT
}
# Main script execution
echo "Setting up network namespaces for Tesla inverters..."
sysctl -w net.ipv4.ip_forward=1
sysctl -w net.ipv4.conf.all.rp_filter=0
sysctl -w net.ipv4.conf.default.rp_filter=0
setup_bridge
ip_addresses=("192.168.1.67" "192.168.1.250")
counter=1
for ip in ${ip_addresses[@]}
do
ip_suffix=$((99 + counter))
table_id=$((ip_suffix))
create_namespace "inverter${counter}" "veth${counter}" "br-veth${counter}" "192.168.92.${ip_suffix}" $table_id $ip
counter=$((counter + 1))
done
# Namespace 1: inverter1
#create_namespace "inverter1" "veth1" "br-veth1" "192.168.92.100" 101 "192.168.1.250"
# Namespace 2: inverter2
#create_namespace "inverter2" "veth2" "br-veth2" "192.168.92.101" 102 "192.168.1.67"
enable_nat
echo "Network namespaces for Tesla inverters have been set up successfully!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment