Created
August 8, 2014 02:14
-
-
Save tchn/b8b175771f090726f888 to your computer and use it in GitHub Desktop.
change ip and mac address of specified nic
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/sh | |
set -o nounset | |
network="10.1.1."; | |
network_bits="24"; | |
gateway="10.1.1.254"; | |
gateway_mac="aa:bb:cc:11:22:33"; | |
nic="$1"; | |
real_macaddr=$(cat /sys/class/net/${nic}/address); | |
current_ip=$(hostname -I | cut -d ' ' -f1); | |
generate_ip() { | |
local ip; | |
for i in $(shuf <(seq $1 $2) | head -n1 ); do ip="${network}${i}"; done; | |
echo "$ip"; | |
} | |
generate_rand_hex() { | |
local words="$1"; | |
local word; | |
word=$(strings /dev/urandom | egrep -o "[a-f0-9]" | head -n "$words" | tr -d "\n" | sed -e "s/\(.\{2\}\)/&:/g" -e "s/:$//g"); | |
echo "$word"; | |
} | |
generate_macaddr() { | |
local macaddr; | |
local high4_1st_oct; | |
local low4_1st_oct; | |
local the_rest; | |
high4_1st_oct=$(generate_rand_hex 1); | |
low4_1st_oct=$(shuf -e 0 2 4 6 8 a c e | head -n1); | |
the_rest=$(generate_rand_hex 10); | |
macaddr="${high4_1st_oct}${low4_1st_oct}:${the_rest}"; | |
echo "$macaddr"; | |
} | |
check_duplicate() { | |
local ip="$1"; | |
local macaddr="$2"; | |
sudo arping -i "$nic" -c1 -r "${ip}" > /dev/null || sudo arping -i "$nic" -c1 -r "$macaddr" > /dev/null; | |
} | |
while true; do | |
echo "$real_macaddr" >> hopip.log; | |
ip=$(generate_ip "$2" "$3"); | |
macaddr=$(generate_macaddr) | |
check_duplicate "$ip" "$macaddr" || echo "$ip" "$macaddr"; break; | |
done | |
sudo ip addr delete "${current_ip}/${network_bits}" dev "$nic"; | |
sudo ip link set "$nic" down; | |
sudo ip link set "$nic" address "$macaddr"; | |
sudo ip link set "$nic" up; | |
sudo ip addr add "${ip}/${network_bits}" dev "$nic"; | |
sudo ip route add default via "$gateway"; | |
sudo arp -s "$gateway" "$gateway_mac"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment