Created
March 28, 2021 02:14
-
-
Save doorbash/a88a28e34e189b2b771b303691264ea6 to your computer and use it in GitHub Desktop.
Load balancing using iptables
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 | |
echo 1 >| /proc/sys/net/ipv4/ip_forward | |
echo 0 >| /proc/sys/net/ipv4/conf/all/rp_filter | |
iptables -F | |
iptables -t mangle -F | |
iptables -t mangle -X | |
iptables -t nat -F | |
iptables -t nat -X | |
iptables -t mangle -N CONNMARK1 | |
iptables -t mangle -A CONNMARK1 -j MARK --set-mark 1 | |
iptables -t mangle -A CONNMARK1 -j CONNMARK --save-mark | |
iptables -t mangle -N CONNMARK2 | |
iptables -t mangle -A CONNMARK2 -j MARK --set-mark 2 | |
iptables -t mangle -A CONNMARK2 -j CONNMARK --save-mark | |
iptables -t mangle -A PREROUTING -p tcp -s 192.168.0.0/16 ! -d 192.168.0.0/16 -m conntrack --ctstate ESTABLISHED,RELATED -j CONNMARK --restore-mark | |
iptables -t mangle -A PREROUTING -p tcp -s 192.168.0.0/16 ! -d 192.168.0.0/16 -m conntrack --ctstate NEW -m statistic --mode random --probability 0.5 -j CONNMARK1 | |
iptables -t mangle -A PREROUTING -p tcp -s 192.168.0.0/16 ! -d 192.168.0.0/16 -m conntrack --ctstate NEW -m mark --mark 0x0 -j CONNMARK2 | |
iptables -t mangle -A PREROUTING ! -p tcp -s 192.168.0.0/16 ! -d 192.168.0.0/16 -m statistic --mode random --probability 0.5 -j MARK --set-mark 1 | |
iptables -t mangle -A PREROUTING ! -p tcp -s 192.168.0.0/16 ! -d 192.168.0.0/16 -m mark --mark 0x0 -j MARK --set-mark 2 | |
iptables -t nat -A POSTROUTING -o wlp7s0 -j MASQUERADE | |
iptables -t nat -A POSTROUTING -o enp8s0 -j MASQUERADE | |
if ! cat /etc/iproute2/rt_tables | grep -q '^251' | |
then | |
echo '251 rt_link1' >> /etc/iproute2/rt_tables | |
fi | |
if ! cat /etc/iproute2/rt_tables | grep -q '^252' | |
then | |
echo '252 rt_link2' >> /etc/iproute2/rt_tables | |
fi | |
ip route flush table rt_link1 2>/dev/null | |
ip route add table rt_link1 default via 192.168.48.1 dev wlp7s0 | |
ip route flush table rt_link2 2>/dev/null | |
ip route add table rt_link2 default via 192.168.1.1 dev enp8s0 | |
ip rule del from all fwmark 0x1 lookup rt_link1 2>/dev/null | |
ip rule del from all fwmark 0x2 lookup rt_link2 2>/dev/null | |
ip rule del from all fwmark 0x2 2>/dev/null | |
ip rule del from all fwmark 0x1 2>/dev/null | |
ip rule add fwmark 1 table rt_link1 | |
ip rule add fwmark 2 table rt_link2 | |
ip route flush cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment