But there was one problem. How do we know the local IP address of Raspberry Pi when it reboots. We will address the same issue in this article.
We will create a python script which will run on every reboot and will send the IP address to a telegram channel.
We are using Raspberry Pi 3 B+ model.
- First we need to create a telegram bot and add it as administrator to the desired telegram channel where you wish to receive the messages.
- Login to your Raspberry pi.
- First create a virtual environment using python3. We will install all the required packages and dependencies in this virtual environment using pip.
- Create a file,
requirements.txt and paste below content in it. It is a list of packages you will require for your future python programms.
aiohttp==3.3.2 async-timeout==3.0.0 attrs==18.1.0 certifi==2018.4.16 chardet==3.0.4 future==0.16.0 idna==2.7 idna-ssl==1.0.1 multidict==4.3.1 pkg-resources==0.0.0 python-telegram-bot==10.1.0 requests==2.7.0 telebot==0.0.3 telepot==12.7 urllib3==1.23 yarl==1.2.6
- Activate the virtual environment and install the telegram package in it using the command
pip install -r requirements.txt.
- Now create a python script with below content.
import telegram import subprocess import time time.sleep(60) bot = telegram.Bot(token="YOUR BOT TOKEN GOES HERE") msg = subprocess.check_output("hostname -I", shell=True).decode('ascii') status = bot.send_message(chat_id="@YOUR CHANNEL ID", text=msg, parse_mode=telegram.ParseMode.HTML) print(status)
We are using
Since this script will be executed after Raspberry pi reboot, we introduced sleep time of 60 seconds in the scripts so that by then Raspberry Pi is connected to the available network.
Then in next line we created the bot. Use your bot token. Refer this article to find out how to get the bot token.
Then run the command
hostname -I and collect its output and send it to the channel.
- Once script is ready, run it manually inside the virtual environment using python3 to test the output.
- Now edit the crontab using command
- Append the below line in crontab.
@reboot ~/py3venv/bin/python3 ~/practice/startup_scripts/ip.py
Use the python3 path and script path accordingly.
Now this script will be executed at every reboot of Raspberry pi and the newly assigned IP address will be sent to you on your telegram channel which you can use to SSH into it.
In the screenshot below you can see, IP address reported by Python script and temprature of Raspberry Pi every 10 minutes.
Purchase Raspberry Pi Starter Kit Here.