In first article we completed the Raspberry Pi Setup, installed OS on SD card and updated the packages. We were connected to Raspberry Pi using LAN cable and external monitor via HDMI cable.
In second article we configured WIFI and enabled SSH. We were not using LAN cable to connect the system. We were able to ssh into Raspberry Pi from our laptop.
Programming on Raspberry Pi with Python: Raspberry Pi Setup
Programming on Raspberry Pi with Python: WIFI and SSH configuration
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.
Telegram Channel and Bot:
- 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.
- Follow this step by step article on how to create a telegram channel and add a telegram bot to it as administrator.
- 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.
- Please refer this article to create virtual environment, to activate it and intalling the packages.
- 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.
- 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.
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)
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.
- How to create completely automated telegram channel with python
Purchase Raspberry Pi Starter Kit Here.