Created
January 27, 2017 21:10
-
-
Save vancluever/a60f80b6cfd5aa8e8c3c6af911442fbd to your computer and use it in GitHub Desktop.
Bash script to calculate a set of subnets off a network address
This file contains hidden or 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
| #!/usr/bin/env bash | |
| # ip_to_decmial takes a dotted-quad IPv4 address and returns the decimal form | |
| # on stdout. | |
| ip_to_decmial() { | |
| local ip_bytes=(${1//./ }) | |
| local ip_decimal=0 | |
| for n in 0 1 2 3; do | |
| ip_decimal=$(( ip_decimal | ip_bytes[n] << 8 * 3 - 8 * n )) | |
| done | |
| echo $ip_decimal | |
| } | |
| # decimal_to_ip takes a decimal IPv4 address and returns the dotted-quad form | |
| # on stdout. | |
| decimal_to_ip() { | |
| local ip_decimal=$1 | |
| local ip_bytes=() | |
| for n in 0 1 2 3; do | |
| ip_bytes+=($(( (ip_decimal >> 8 * 3 - 8 * n) & 255 ))) | |
| done | |
| echo "${ip_bytes[0]}.${ip_bytes[1]}.${ip_bytes[2]}.${ip_bytes[3]}" | |
| } | |
| dec=$(ip_to_decmial "$1") | |
| shift | |
| while (( "$#" )); do | |
| params=(${1/\*/ }) | |
| shift | |
| n=1 | |
| while [ "${n}" -le "${params[0]}" ]; do | |
| echo "$(decimal_to_ip "${dec}")/${params[1]}" | |
| dec=$((dec + 2 ** (32-params[1]))) | |
| ((n++)) | |
| done | |
| done |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run this script like so:
This would calculate the first 4
/24s, and then the next 8/25s, starting from10.0.0.0.Output: