Created
December 26, 2018 09:54
-
-
Save oswalpalash/20b44568fb75462731d3e0500dbff069 to your computer and use it in GitHub Desktop.
Write a bash script to subdivide a given CIDR /24 and smaller subnets into a pre-defined number of smaller subnets.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
CIDR="" | |
BASE_IP="" | |
PARTS="" | |
validate() { | |
if [[ $BASE_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then | |
: | |
else | |
echo "IP Address incorrect." | |
exit | |
fi | |
if [[ -z $CIDR ]]; then | |
echo "CIDR not entered" | |
die | |
fi | |
if [[ -z $PARTS ]]; then | |
echo "PARTS not entered." | |
die | |
fi | |
} | |
sanitise() { | |
CIDR=$(echo $1 | awk -F "/" '{print $2}') | |
BASE_IP=$(echo $1 | awk -F "/" '{print $1}') | |
PARTS=$2 | |
validate | |
} | |
base2() { | |
local x=0 | |
for (( y=$1-1 ; $y > 0; y >>= 1 )) ; do | |
let x=$x+1 | |
done | |
echo $x | |
} | |
fixip() { | |
if [ $IP_OFFSET -ge 256 ]; then | |
IP_SET=$(echo $IP_PREFIX | cut -d '.' -f3 ) | |
ADDITIVE_OFFSET=$(( IP_OFFSET / 256 )) | |
NEW_IP_PREFIX=$(echo $(echo $IP_PREFIX | cut -d '.' -f1-2)"."$(( IP_SET + ADDITIVE_OFFSET ))) | |
NEW_IP_OFFSET=$(( IP_OFFSET % 256 )) | |
IP_OFFSET=$NEW_IP_OFFSET | |
IP_PREFIX=$NEW_IP_PREFIX | |
fi | |
} | |
calculate_ips() { | |
NUM_BITS=$(( 32 - CIDR )) | |
NUM_IPS=$(( 2 ** NUM_BITS )) | |
SUBSET=$(( NUM_IPS / PARTS )) | |
IP_PREFIX=$(echo $BASE_IP | cut -d '.' -f1-3) | |
IP_START_OFFSET=$(echo $BASE_IP | cut -d '.' -f4) | |
MINIMUM_IPS_REQURED=$(( SUBSET * 3 + SUBSET )) | |
if [ $NUM_IPS -le $MINIMUM_IPS_REQURED ]; then | |
for(( i=0; i < $PARTS; i++)) { | |
IP_OFFSET=$(( SUBSET * i )) | |
IP_OFFSET=$(( IP_OFFSET + IP_START_OFFSET )) | |
SUBSET_CIDR=$(( 32 - $(base2 SUBSET ) )) | |
HOSTS=$(( ${SUBSET} - 3 )) | |
if [ $HOSTS -ge 0 ];then | |
fixip | |
echo "subnet=${IP_PREFIX}.${IP_OFFSET}/$SUBSET_CIDR network=${IP_PREFIX}.${IP_OFFSET} broadcast=${IP_PREFIX}.$(( $(( IP_OFFSET + SUBSET - 1 )) % 256 )) gateway=${IP_PREFIX}.$(( IP_OFFSET + 1 )) hosts=$(( ${SUBSET} - 3 ))" | |
else | |
echo "Not Enough IPs" | |
exit | |
fi | |
} | |
else | |
echo "Not Enough IPs" | |
fi | |
} | |
main() { | |
sanitise $@ | |
calculate_ips | |
} | |
usage() { | |
echo "./subnetter.sh <ip> <no of subnets>" | |
} | |
die () { | |
usage | |
exit 1 | |
} | |
[ "$#" -ge 1 ] || die | |
main $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment