Skip to content

Instantly share code, notes, and snippets.

@wdog
Last active January 16, 2020 10:19
Show Gist options
  • Save wdog/59db54a8599a4fa0951e1af57431d4c5 to your computer and use it in GitHub Desktop.
Save wdog/59db54a8599a4fa0951e1af57431d4c5 to your computer and use it in GitHub Desktop.
Simple script for vlan
#!/bin/bash
DEFADPATER=eno1
DEFVLAN=300
DEFNET=10.137.1.2
RED='\033[0;31m'
GREEN='\033[0;32m'
INFO='\033[0;36m'
NC='\033[0m' # No Color
# Returns true if iface exists and is up, otherwise false.
function ifup {
typeset output
output=$(ip link show "$ADAPTER.$VLAN" up) && [[ -n $output ]]
}
function up(){
if ! ifup &>/dev/null; then
echo -e "${GREEN}"
echo -e "CREATING VLAN $ADAPTER.$VLAN ... \c"
echo -e "${NC}\c"
sudo ip link add link $ADAPTER name $ADAPTER.$VLAN type vlan id $VLAN
sudo ip addr add $NET/24 dev $ADAPTER.$VLAN
sudo ip link set dev $ADAPTER.$VLAN up
echo -e "${GREEN}\c"
echo -e "[DONE]\c"
echo -e "${NC}"
echo -e "${INFO}"
echo -e "ADD MANUALLY SOME ROUTE IF NEEDED"
echo -e "sudo ip route add 10.137.0.1 via 10.137.1.254 dev $ADAPTER.$VLAN"
echo -e "${NC}"
else
status
fi
}
function down(){
echo -e "${GREEN}"
echo -e "REMOVING VLAN $ADAPTER.$VLAN ... \c"
echo -e "${NC}\c"
sudo ip link delete $ADAPTER.$VLAN &>/dev/null
echo -e "${GREEN}\c"
echo -e "[DONE]"
echo -e "${NC}"
}
function status (){
if ifup &>/dev/null; then
echo -e "${GREEN}"
echo -e "LINK $ADAPTER.$VLAN UP"
else
echo -e "${RED}"
echo -e "LINK $ADAPTER.$VLAN DOWN"
fi
echo -e ""${NC}
}
function usage(){
echo ""
echo "Usage: $0 [params] up|down|restart|status"
echo -e "\tPARAMS:"
echo -e "\t-v vlan"
echo -e "\t-d adapter"
echo -e "\t-n ip"
echo -e "\t-h "
exit 1 # Exit script after printing help
}
# --- SETUP ---
while getopts "v:d:n:" opt
do
case "$opt" in
v) VLAN="${OPTARG:-$DEFVLAN}";;
d) ADAPTER="${OPTARG:-$DEFADPATER}";;
n) NET="${OPTARG:-$DEFNET}";;
?|h) usage;;
esac
done
VLAN=${VLAN:-$DEFVLAN}
ADAPTER=${ADAPTER:-$DEFADPATER}
NET=${NET:-$DEFNET}
OPERATION=${!#}
if [ -z $OPERATION ]; then
usage
fi
case "$OPERATION" in
'up')
up
;;
'down')
down
;;
'restart')
down ; sleep 1 ; up
;;
'status')
status
;;
*)
usage
exit 1
;;
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment