Helper Scripts

Helper Scripts

This article is dedicated to small scripts that can help make life easier.

IP Conversion

The quad dot IP notation is most used in networking, but sometimes under the hood hex is used. Therefore, it is convenient to be able to quickly convert hexadecimal IP notation to decimal and vice versa. The following script can be used to convert hex style IPs (as used by Check Point for example in their fw tab commands) to decimal:

#!/bin/bash
#hex2dec.sh

function convert {
    INP="$1"
    if [[ $INP =~ ^[0-9A-Fa-f]{8}.*$ ]] ; then
        o1="$((16#${INP:0:2}))"
        o2="$((16#${INP:2:2}))"
        o3="$((16#${INP:4:2}))"
        o4="$((16#${INP:6:2}))"
        printf "%d.%d.%d.%d" $o1 $o2 $o3 $o4
    else
        printf "%s" "$INP"
    fi
}

if [[ -t 0 ]]; then
    for var in "$@"
    do
        convert "$var"
    done
    printf "\n"
else
    while read -r line; do
        for word in $line:
        do
            convert "$word"
            printf ' '
        done
        printf "\n"
    done <<< "$(cat)"
fi

And sometimes you want to grep for a certain IP, so it also a good idea to have convenience function to quickly translate an IP adres to decimal:

#!/bin/bash
#dec2hex.sh

function convert {
    INP="$1"
    if [[ $INP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] ; then
        IFS='.'
        read -ra OCTETS <<< "$INP"
        for OCTET in "${OCTETS[@]}"; do
            printf "%02x" "$OCTET"
        done
    else
        printf "Input is not a valid IP"
    fi
}

if [[ -t 0 ]]; then
    for var in "$@"
    do
        convert "$var"
    done
    printf "\n"
fi