Переключение интернета

Материал из darklurker wiki
Перейти к: навигация, поиск
  • Конфигурация /etc/sysconfig/internet-monitoring
IF_MAIN="vlan0101"
GW_MAIN="176.222.250.225"
IF_BACKUP="vlan0102"
GW_BACKUP="212.220.153.161"
  • Скрипт
# Setup

if [ -f /etc/sysconfig/internet-monitoring ]; then
        source /etc/sysconfig/internet-monitoring
                                       else
        echo "Config file /etc/sysconfig/internet-monitoring not found"
        exit 1
fi

# Adding routing tables

grep -q ^10 /etc/iproute2/rt_tables
RETVAL=$?
[ $RETVAL -ne 0 ] && echo "10 Main" >> /etc/iproute2/rt_tables
grep -q ^11 /etc/iproute2/rt_tables
RETVAL=$?
[ $RETVAL -ne 0 ] && echo "11 Backup" >> /etc/iproute2/rt_tables

# Calculate parameters
ADDR_MAIN=`ip -o -f inet addr show dev $IF_MAIN | awk {' print $4 '}`
NETWORK_MAIN=`ipcalc $ADDR_MAIN -n | awk -F = {' print $2 '}`
MASK_MAIN=`ipcalc $ADDR_MAIN -p | awk -F = {' print $2 '}`
ADDR_MAIN=`echo $ADDR_MAIN | awk -F / {' print $1 '}`
CONNECTED_MAIN="$NETWORK_MAIN/$MASK_MAIN"

ADDR_BACKUP=`ip -o -f inet addr show dev $IF_BACKUP | awk {' print $4 '}`
NETWORK_BACKUP=`ipcalc $ADDR_BACKUP -n | awk -F = {' print $2 '}`
MASK_BACKUP=`ipcalc $ADDR_BACKUP -p | awk -F = {' print $2 '}`
ADDR_BACKUP=`echo $ADDR_BACKUP | awk -F / {' print $1 '}`
CONNECTED_BACKUP="$NETWORK_BACKUP/$MASK_BACKUP"


GO_MAIN="ip route replace default via $GW_MAIN"
GO_BACKUP="ip route replace default via $GW_BACKUP"

ip route add $CONNECTED_MAIN dev $IF_MAIN src $ADDR_MAIN table 10
ip route add default via $GW_MAIN table 10
ip rule add from $ADDR_MAIN table 10

ip route add $CONNECTED_BACKUP dev $IF_BACKUP src $ADDR_BACKUP table 11
ip route add default via $GW_BACKUP table 11
ip rule add from $ADDR_BACKUP table 11


STATE=-1


while true; do
	#count for recieved packets on main channel
	CHECK=`ping -I $ADDR_MAIN -c 5 8.8.4.4 | grep transmitted | awk '{print $4}'`

if [[ $CHECK -eq 0 ]]; then 

	{
	#Main channel is down
	if [[ $STATE -ne 1 ]]; then
		{
		`$GO_BACKUP`
                logger -t Internet Main channel down
		STATE=1
		}
	fi
	} else {
	#Main channel is up
	if [[ $STATE -ne 0 ]]; then
		{
                `$GO_MAIN`
                logger -t Internet Main channel up
                STATE=0
		}
	fi
	}
fi

sleep 5
done 

  • Systemd (/lib/systemd/system/internet-monitoring.service)
[Unit]
Description=Internet monitoring service (with backup)
After=syslog.target network.target

[Service]
Type=simple
ExecStart=/bin/bash /usr/sbin/internet-monitoring.sh

[Install]
WantedBy=multi-user.target