Friday, March 22, 2024

USB Shutdown Key

While building up a raspberry pi system recently I needed an easy way to shutdown the device without having to ssh into it.

I had an idea pop into my head, what if I plug in a usb drive and maybe it automatically runs a script on the usb key, or something and powers the device down.

Well after a bit of googling it turns out.... you can use udev rules to do what I want, and no need to put anything on my drive.

This is the process.

First, you figure out the vendor ID and the product ID of the usb key. 

The way I did this was by running lsusb and noting the devices, since this is a raspberry pi, the list was short.

I then plugged the usb drive in, and ran lsusb again. I noted which device it was.

Then I ran lsusb -v to get the values for idVendor and idProduct. 

I then copied them into this line (remember not to include the 0x), in the applicable spots. 

ACTION=="add" , ATTRS{idProduct}=="2168" , ATTRS{idVendor}=="0ea0" , RUN+="/usr/local/bin/"

I then placed that line into this file:

sudo nano /etc/udev/rules.d/99-usb-shutdown.rules

Next, I edited /usr/local/bin/ to contain the following:

#!/bin/sh sudo shutdown -h now 

Finally I ran 

sudo chmod +x /usr/local/bin/

on the file and rebooted, just to make sure everything was stable.

Now when I plug in the usb drive, bam, it just shuts down.

Thanks to this post for the details they used, which was exactly what I did with the minor note that I used lsusb -v (they just mentioned using lsusb ;))!