init.d script for bridging two network cards

This is an init.d script I wrote some time ago that creates a virtual bridge adapter bridging two NICs. Of course you will need bridge-utils installed. To enable the script, copy the code below to a file /etc/init.d/bridge and (in debian/ubuntu) run:

update-rc.d bridge defaults

Note that it takes 30s for the bridge to become active.


#!/bin/sh
# Script to start|stop|restart bridging of two network devices
# Written by Jochen Miroll 05/28/05

ADDRESS="10.10.0.10/24"
GATEWAY="10.10.0.1"
DEV1=eth0
DEV2=eth1
#ONSTOP is the device that gets the IP address when bridging is stopped
ONSTOP=$DEV1
BR=bridge
SYSPATH=/sys/class/net
#userspace tools
BRCTL=/usr/sbin/brctl
IP=/bin/ip

#bail out if our userspace tools are not installed
test -f $BRTCL || exit 0
test -f $IP || exit 0

case "$1" in
start)
echo -n "Bridging $DEV1 and $DEV2: "

if [ -d "$SYSPATH/$BR" ]; then
echo "$BR already exists."
exit 1
fi
if [ ! -d "$SYSPATH/$DEV1" ]; then
echo "$DEV1 does not exist."
exit 1
fi
if [ ! -d "$SYSPATH/$DEV2" ]; then
echo "$DEV2 does not exist."
exit 1
fi

$IP addr flush dev $DEV1
$IP addr flush dev $DEV2
$IP link set dev $DEV1 down
$IP link set dev $DEV2 down
sleep 1
$BRCTL addbr $BR
$BRCTL addif $BR $DEV1
$BRCTL addif $BR $DEV2
$IP addr add $ADDRESS brd + dev $BR
$IP link set dev $DEV1 up
$IP link set dev $DEV2 up
$IP link set dev $BR up

route add default gw $GATEWAY dev $BR
echo "$BR is now $ADDRESS."
;;
stop)
echo -n "Stopping bridge: "
if [ ! -d "$SYSPATH/$BR" ]; then
echo "$BR does not exist."
exit 0
fi
if [ ! -d "$SYSPATH/$ONSTOP" ]; then
echo "$ONSTOP does not exist."
exit 0
fi

$IP link set dev $DEV1 down
$IP link set dev $DEV2 down
$IP link set dev $BR down
sleep 1
$BRCTL delif $BR $DEV1
$BRCTL delif $BR $DEV2
$BRCTL delbr $BR
$IP addr flush dev $ONSTOP
$IP addr add $ADDRESS brd + dev $ONSTOP
$IP link set dev $ONSTOP up

echo "$ONSTOP is now $ADDRESS."
;;
restart)
$0 stop
sleep 2
$0 start
if [ "$?" != "0" ]; then
exit 1
fi
/etc/init.d/dhcp3-server restart
;;
*)
echo "Usage: /etc/init.d/bridge {start|stop|restart}"
exit 1
esac

exit 0


This page is powered by Blogger. Isn't yours?