Out of habit, whenever I turn on my laptop, I open five instances of PuTTY and connect to each of my Raspberry Pi devices. Then, I check for updates on each by running
sudo apt-get update and
sudo apt-get dist-upgrade. Over the Golden Week holiday, I thought, “Why don’t I create a script that runs the update commands across all five devices?”
Creating the script
First, let’s open PuTTY and create a script in our user directory:
sudo nano update_all.sh
In this file, let’s add the following content:
for ip in [ip1] [ip2] [ip3] [ip4] [ip5]
ssh pi@$ip 'sudo apt-get update && sudo apt-get dist-upgrade'
Replace each of the
[ip#] placeholders with the IP address of each of your Raspberry Pi devices. Also, remove any of the placeholders that you don’t need.
Running the script
We need to make this script executable, so let’s run:
sudo chmod +x update-all.sh
And now we can run the script:
When you first run the script, the prompt in PuTTY will ask if you want to proceed.
If you type yes, the IP address will be added to the list of trusted hosts on the Raspberry Pi that runs the script. The prompt will ask you for the password for each device. Then, the script will run the update and upgrade commands.
When you add devices to the list of trusted hosts, you’ll still need to enter the password for each device when running the script. This is because I didn’t want to include the password in plaintext for each device in the script.
Typing no skips the device with the specified IP address. In this case, the script will not run the update or upgrade commands on that device.
The script will skip an IP address that it can’t find. For example, I included one of my Raspberry Pi devices that has a static IP for Ethernet and WLAN connections. Since the device is usually on a WLAN connection, the IP address for the Ethernet connection is skipped.
You could repurpose this script to run other commands, such as shutdown, reboot, or component installation. Imagine joining 10 Kubernetes worker nodes to a master node by using a single script? That would save a significant amount of time!