Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Validates the VLAN configuration on an interface by creating a tagged subinterface, assigning the next available address, and sending a ping to the provided gateway IP address.
#!/usr/bin/env bash
# vlan-check.sh
#
# Validates the VLAN configuration on an interface
# by creating a tagged subinterface, assigning the
# next available address, and sending a ping to the
# provided gateway IP address.
#
# Supports Ubuntu and RHEL/CentOS. I think.
#
if [[ ( $# -ne 3 ) && ( $# -ne 4 ) ]]; then
echo "usage: ${0} <interface> <vlan-id> <gateway-ip/cidr> [ip]" 1>&2
echo " ex: ${0} eth0 10 192.168.1.1/24" 1>&2
exit 2
fi
# Bash string manipulations Cliffs Notes
#
# ${string%substring}
# Deletes shortest match of $substring from back of $string.
#
# ${string#substring}
# Deletes shortest match of $substring from front of $string.
#
# To delete the longest match, use the symbol twice, e.g.:
#
# ${string##substring}
#
# http://tldp.org/LDP/abs/html/string-manipulation.html
#
INTERFACE="$1"
VLAN="$2"
GATEWAY_IP="${3%/*}"
CIDR="/${3##*/}"
VLAN_INTERFACE_IP="$4"
ADD="vconfig add"
REMOVE="vconfig rem"
get_distro() {
if [[ -f "/etc/redhat-release" ]]; then
DISTRO="rhel"
elif [[ -f "/etc/debian_version" ]]; then
DISTRO="ubuntu"
else
echo "Unrecognized distribution. Aborting."
exit 2
fi
}
is_ubuntu() {
[[ "$DISTRO" == "ubuntu" ]]
}
save_result() {
"$@"
RESULT=$?
}
clean_up() {
if [[ -n "${VLAN_TAGGED_INTERFACE}" ]]; then
${REMOVE} ${VLAN_TAGGED_INTERFACE} &> /dev/null
fi
}
trap clean_up EXIT
get_distro
# Install dependencies
if is_ubuntu; then
apt-get update > /dev/null
apt-get install -qy vlan > /dev/null
else
yum install -q -y vconfig > /dev/null
fi
modprobe 8021q
# Create tagged subinterface
${ADD} ${INTERFACE} ${VLAN}
VLAN_TAGGED_INTERFACE="${INTERFACE}.${VLAN}"
ifconfig ${VLAN_TAGGED_INTERFACE} up
if [[ -z "$VLAN_INTERFACE_IP" ]]; then
# Find IP address by incrementing the last octect of the
# gateway's IP address. It's ghetto but it works.
FIRST_THREE_OCTETS="${GATEWAY_IP%.*}"
LAST_OCTET=$((${GATEWAY_IP##*.} + 1))
while ping -c 1 ${FIRST_THREE_OCTETS}.${LAST_OCTET} > /dev/null; do
LAST_OCTET=$((LAST_OCTET + 1))
done
VLAN_INTERFACE_IP="${FIRST_THREE_OCTETS}.${LAST_OCTET}"
fi
ip a a ${VLAN_INTERFACE_IP}${CIDR} dev ${VLAN_TAGGED_INTERFACE}
save_result ping -c 1 -I ${VLAN_TAGGED_INTERFACE} ${GATEWAY_IP}
if [[ ${RESULT} -eq 0 ]]; then
echo -e "\e[1;32mSUCCESS\e[0m"
else
echo -e "\e[1;31mFAILURE\e[0m"
fi
exit ${RESULT}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment