Tuesday, March 12, 2013

Shutdown Linux nicely with a USB stick the right way

Forget everything I wrote in my previous post. Like Andrew pointed out in the comments on my youtube video and the blog, running a cron job every minute isn't really optimal. There is a better way to do it.


The fun part is that it doesn't require autofs since it uses udev rules and can find out the id of a USB stick (or any other device I guess) upon connection instead of going through the mounting process. At the same time it also manages quite nicely renders my script obsolete since you can issue "shutdown -h now" directly. Oh, did   mention it's A LOT faster. 

Well enough with the talk here's how you do it: 

Find out the vendorId and productId of your USB stick: 
$ lsusb
Here's my output, the numbers you want are the ones after "ID" the first one is the vendorId and the latter productId:
Bus 001 Device 003: ID 0781:7114 SanDisk Corp. Cruzer Mini
Bus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

Then create an aptly named file in: /etc/udev/rules.d/ I went with: 100-usb-device-action.rules 

Then add the following line, just substitute your vendorId and your productId
ACTION=="add", ATTRS{idVendor}=="0781", ATTRS{idProduct}=="7114", RUN+="/sbin/shutdown -h now"

That's it! Your done. Insert that USB device and watch your system shutdown in a nice way. 

2 comments:

  1. by doing this we wont even need a usb stick right , like we could use a serial device like a ftdi chip to shutdown a linux system right ??

    ReplyDelete
    Replies
    1. It's been a while since you commented but it's been even longer since I messed around with this so I can't say for sure. But my guess would be yes, pretty much anything that plugs in to the USB port could be used to run a commmand.

      Delete