Created
June 8, 2015 17:17
-
-
Save evilsocket/b9a91775dbde14b0dab4 to your computer and use it in GitHub Desktop.
Periodically scan your network searching for your Raspberry Pi board and update your /etc/hosts file with its ip address.
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 | |
# | |
# Periodically scan your network searching for your | |
# Raspberry Pi board and update your /etc/hosts file | |
# with its ip address. | |
# | |
# Copyleft by Simone 'evilsocket' Margaritelli | |
# http://www.evilsocket.net | |
# evilsocket at gmail dot com | |
# | |
# seconds to sleep time between one check and the next one | |
DELAY=5 | |
# put your subnet here | |
SUBNET="192.168.1.0/24" | |
# put the first 2 octects of the Pi mac address | |
HWADDR="E8:94" | |
# hostname to put in /etc/hosts file | |
HOSTNAME="pi" | |
if [[ $EUID -ne 0 ]]; then | |
echo "This script must be run as root" 1>&2 | |
exit 1 | |
fi | |
while : | |
do | |
echo "@ Searching for Raspberry Pi address ..." | |
PIADDR=$(nmap -sP "$SUBNET" | awk "/^Nmap/{ip=\$NF}/$HWADDR/{print ip}") | |
PIADDR=$(echo "$PIADDR" | sed -e "s/[^0-9\.]//g") | |
if [ -z "$PIADDR" ]; then | |
echo "! Could not find Raspberry Pi on network $SUBNET" | |
else | |
echo "@ Found '$PIADDR', updating /etc/hosts file ..." | |
FOUND=$(cat /etc/hosts | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b\s+$HOSTNAME\$") | |
if ! [[ -z "$FOUND" ]] ; then | |
echo "@ Removing old entry ..." | |
cat /etc/hosts | grep -vw "$FOUND" > /etc/hosts.bak | |
mv /etc/hosts.bak /etc/hosts | |
fi | |
echo "@ Updating /etc/hosts file ..." | |
echo "$PIADDR $HOSTNAME" >> /etc/hosts | |
fi | |
sleep $DELAY | |
done |
If more than a RPI are present in a network this script will slowly fill the /etc/hosts file.
example:
@ Searching for Raspberry Pi address ...
@ Found '192.168.1.2
192.168.1.14
192.168.1.20
192.168.1.21
192.168.1.109
192.168.1.137
192.168.1.240
192.168.1.254', updating /etc/hosts file ...
Leaving the script running in this condition I had, after 3 loops:
(/etc/hosts):
192.168.1.2
192.168.1.14
192.168.1.20
192.168.1.21
192.168.1.109
192.168.1.137
192.168.1.240
192.168.1.2
192.168.1.14
192.168.1.20
192.168.1.21
192.168.1.109
192.168.1.137
192.168.1.240
192.168.1.2
192.168.1.14
192.168.1.20
192.168.1.21
192.168.1.109
192.168.1.137
192.168.1.240
192.168.1.254 pi
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not set your router to serve a static ip address using the pi's MAC Address ?
So if the power go down when it turns on again the DHCP server sets automatically the ip address for your pi and you can find it everytime.