Skip to content

Instantly share code, notes, and snippets.

@allegrem
Last active April 17, 2018 04:42
Show Gist options
  • Save allegrem/5529064 to your computer and use it in GitHub Desktop.
Save allegrem/5529064 to your computer and use it in GitHub Desktop.
A little script which retrieves the MAC and IP addresses of the first active Raspberry Pi on the local network, and then connects to it through SSH.
#!/bin/bash
#Get the IP address of the Raspberry Pi and connect to it through SSH.
echo "*************** CONNECT-PI ***************"
echo "* /!\ You must reboot the Raspberry Pi *"
echo "* now in order to make this script work. *"
echo "******************************************"
echo
echo -n "Getting MAC address... "
MAC=`sudo tshark -n -i eth0 -f "port 67 and port 68 and ether[6:2] == 0xb827 and ether[8:1] == 0xeb" -T fields -e eth.src -c 1 2> /dev/null`
echo $MAC
echo -n "Getting IP address... "
IP=`sudo tshark -n -i eth0 -f "ether src host $MAC and arp" -T fields -e arp.src.proto_ipv4 -c 1 2> /dev/null`
echo $IP
echo -n "Waiting for SSH to start..."
while true; do
nc -z $IP 22 && break;
sleep 2
echo -n "."
done
echo
echo "Connecting through SSH..."
ssh pi@$IP
@allegrem
Copy link
Author

allegrem commented May 6, 2013

The script is based on the network requests performed by the Pi on startup.
First, a broadcast DHCP Request is sent (the script intercepts it based on
the Raspberry MAC vendor prefix), which gives us its complete MAC address.
Then, it has to answer to the DHCP server. That's why it sends a broadcast
ARP request to ask for its IP address. Since this request is broadcast, we
can intercept it and get the IP address of the Pi.
Finally, we scan the SSH port (22) until it opens, which lets us connect
to the Pi.

Some assumptions are done in this script :

  • you want to connect to the user 'pi' (but it's easy to change if necessary)
  • there is a working DHCP server in your local network
  • you didn't modify the MAC address of your Pi
  • you have normal settings on your computer (port numbers, firewall, ...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment