Skip to content

Instantly share code, notes, and snippets.

@krsoninikhil
Last active May 5, 2016 13:36
Show Gist options
  • Save krsoninikhil/9f2b7575281f5b4c1c6b87cb836a68f6 to your computer and use it in GitHub Desktop.
Save krsoninikhil/9f2b7575281f5b4c1c6b87cb836a68f6 to your computer and use it in GitHub Desktop.
Random MAC address generator

Example

  • To generate dataset: bash random-mac.sh 10

  • To search by device id: bash random-mac.sh -s 8

  • Replace the file name with the actual path to the file.

  • Replace replace 10 with actual number of devices.

  • Repalce 8 with the device id to be searched.

The result will be saved in dataset.csv file.

#!/bin/bash
# this will generate n random mac-48 addresses
# define organisational unique identifier (OUI), if any and the separator to be used like ':' or '-'
OUI=''
SEP=':'
DATA_SET='dataset.csv'
# functions for generating half mac address i.e three ocatates at a time
get_hex(){
# generating a random number between 0 to 15 and convering to hexadecimal
m=$(shuf -i0-15 -n1)
hex=$(printf "%x" $m)
echo "$hex"
}
three_oct(){
three_oct="$(get_hex)$(get_hex)$SEP$(get_hex)$(get_hex)$SEP$(get_hex)$(get_hex)"
echo $three_oct
}
generate(){
printf 'Generating MAC addresses'
echo 'Device Id,Ethernet MAC Id, Wifi Interface MAC Id' > "$DATA_SET"
for ((i=1;i<=$1;i++)); do
if [[ $OUI != '' ]]; then
mac_eth="$OUI$SEP$(three_oct)"
mac_wl="$OUI$SEP$(three_oct)"
else
mac_eth="$(three_oct)$SEP$(three_oct)"
mac_wl="$(three_oct)$SEP$(three_oct)"
fi
echo "$i,$mac_eth,$mac_wl" >> "$DATA_SET"
printf '.'
done
echo ".Done. Saved in $DATA_SET"
}
# for seaching data in $DATA_SET
search(){
if [[ -f $DATA_SET ]]; then
line=$(sed -n "$(($1+1))p" < "$DATA_SET")
if [[ $line ]]; then
IFS=',' read -ra data <<< "$line"
echo "Data for device id $1:"
echo "Ethernet MAC address: ${data[1]}"
echo "Wifi interface MAC address: ${data[2]}"
else
echo "$1: Device id not found"
fi
else
echo "$DATA_SET: No such file present."
fi
}
# main execution
if [[ $# == 1 && $1 =~ ^[0-9]+$ ]]; then
generate $1
elif [[ $# == 2 && $1 == '-s' && $2 =~ ^[0-9]+$ ]]; then
search $2
else
echo 'Please provide the valid number of devices as argument to generate dataset.'
echo 'To search data of any device use "-s" option followed by the device id.'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment