El siguiente script en bash es el primer prototipo de LoadBalancer para un servicio TCP en dos o mas servidores simultaneamente utilizando iptables.
#!/bin/bash local_ip="10.10.50.81" ip1="10.10.96.50" ip2="10.10.50.106" tcp_port="80" #Se valida que los servicios esten disponibles nmap $ip1 -p $tcp_port | grep -i open >> /dev/null service1=$? nmap $ip2 -p $tcp_port | grep -i open >> /dev/null service2=$? let status=$service1+$service2 echo "Valor: $status" let remakerules=10 while [ 0 -eq 0 ]; do if [ "$remakerules" != "$status" ]; then # You need these system settings. echo 1 > /proc/sys/net/ipv4/ip_forward for f in /proc/sys/net/ipv4/conf/*/rp_filter ; do echo 1 > $f ; done # Clear iptables/netfilter settings. iptables -F iptables -X iptables -t nat -F iptables -t nat -X iptables -t filter -F iptables -t filter -X iptables -t mangle -F iptables -t mangle -X iptables -P INPUT ACCEPT iptables -P OUTPUT ACCEPT iptables -P FORWARD ACCEPT iptables -t nat -P PREROUTING ACCEPT iptables -t nat -P POSTROUTING ACCEPT if [ "$service1" == "0" -a "$service2" == "0" ]; then #Los dos servicios estan disponibles iptables -t nat -A PREROUTING -p tcp -d $local_ip --dport $tcp_port -m state --state NEW -m statistic --mode random --probability .5 -j DNAT --to $ip1:$tcp_port iptables -t nat -A PREROUTING -p tcp -d $local_ip --dport $tcp_port -m state --state NEW -m statistic --mode random --probability .5 -j DNAT --to $ip2:$tcp_port else if [ "$service2" == "0" ]; then #Unicamente el servicio2 esta arriba iptables -t nat -A PREROUTING -p tcp -d $local_ip --dport $tcp_port -m state --state NEW -m statistic --mode nth --every 1 --packet 0 -j DNAT --to $ip2:$tcp_port else if [ "$service1" == "0" ]; then #Unicamente el servicio1 esta arriba iptables -t nat -A PREROUTING -p tcp -d $local_ip --dport $tcp_port -m state --state NEW -m statistic --mode nth --every 1 --packet 0 -j DNAT --to $ip1:$tcp_port else echo "CRITICAL: Los dos Servicios estan abajo" fi fi fi iptables -A INPUT -j ACCEPT iptables -A OUTPUT -j ACCEPT iptables -A FORWARD -j ACCEPT iptables -A INPUT -j LOG --log-prefix "iptables: " --log-level 4 iptables -A OUTPUT -j LOG --log-prefix "iptables: " --log-level 4 iptables -A FORWARD -j LOG --log-prefix "iptables: " --log-level 4 iptables -t nat -A POSTROUTING -j MASQUERADE echo "Cambio de reglas..." fi #sleep 1200 sleep 1 #Se valida que los servicios esten disponibles nmap $ip1 -p $tcp_port | grep -i open >> /dev/null service1=$? nmap $ip2 -p $tcp_port | grep -i open >> /dev/null service2=$? let remakerules=$status let status=$service1+$service2 echo "Valor: $status" done