Thursday, May 29, 2014

Make Raspberry Pi (and other SBCs) report it's IP address when it starts up.

You can also track power on events and other information in this way. First, create a script, let's call it reportip.sh:

#!/bin/bash
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
  result = ""
  printf -v result "192.168.1.2/rpi.php?id=pi-R&ip=%s" "$_IP"
  echo "$result"
  curl -u username:password $result
fi


What's going on here?
First it gets the IP address and assigns it to a variable $_IP.
It displays a message so if you do happen to have a display plugged in then you'll see what the IP address is without logging in.
It builds a $result variable that is a url. In this case I have a fictional web server at 192.168.1.2, a PHP script called rpi.php runs on it that can take some values and log them to a database. This is a very simple script that is setup to log to a SQLite database but could easily be rewritten to point to MySQL or your favorite database.
It then uses curl to call upon that url in order to set things in motion. I'm using the -u switch to specify a simple digest username and password.

Then you can put this into your /etc/rc.local
This is wildly insecure if you leave it in a user's home directory since whatever is in the script will be executed with root privileges on startup so don't do that in your day job. You can run it with sudo -u username /home/user/reportip.sh to run it with lesser privileges or put it elsewhere.
Once this is setup then every time your pi starts, it will get an IP and then hit your server to report what IP it got. Then you can go to that page and see what it is.

I actually need to rewrite that PHP script, it was lost in a hard drive crash earlier this year. Look for it soon, I will put it up on my GitHub account.

No comments:

Post a Comment