#!/bin/bash # powersw - power switch utility. # Turn on and off the power to various external devices. # # This knows about two ways to control the power: # (1) Control from a USB hub. The hubpower program is used to actually # toggle the power. This script adds a layer on top of that to find # the right port on the right hub. # (2) Control from an IP Power 9258 power switch. This script sends an # HTTP request to the switch to toggle the power. # # By Philip Endecott, 2010. # I hearby place this code in the public domain. usage() { echo "Usage: powersw [--delay ] [on|off]" echo "See /etc/powersw.conf for device configuration." exit 1 } find_hub() { # We're looking for a hub with no devices connected to it and per-port # power switching. hub_bus_dev=`lsusb -v | tr -d ':' | awk '/^Bus [0-9]+ Device [0-9]+/ { bus=$2; dev=$4; ppps=0; any_devs=0; } /Per-port power switching/ { ppps=1; } /Port.*connect/ { any_devs=1; } /^$/ { if (ppps && !any_devs) exit; } END { if (ppps && !any_devs) printf("%s:%s",bus,dev); } '` if [ -z "${hub_bus_dev}" ] then echo "Can't find power control hub" exit 1 fi } find_device() { l=`cat /etc/powersw.conf | awk '!/^#/ && !/^$/ && $1=="'$device'"'` if [ -z "${l}" ] then echo "Can't find requested device '${device}' in /etc/powersw.conf" exit 1 fi controller=`echo $l | awk '{print $2}'` portnum=`echo $l | awk '{print $3}'` } do_hubpower() { hubpower "${hub_bus_dev}" power "${portnum}" "${action}" } do_powerswitch() { case "${action}" in on) state=1 ;; off) state=0 ;; *) echo "Unknown state '${state}'" ; exit 1 ;; esac url="http://admin:12345678@powerswitch/Set.cmd?CMD=SetPower+P$((59+${portnum}))=${state}" echo $url wget "${url}" } do_switch() { case "${controller}" in usb) do_hubpower ;; powerswitch) do_powerswitch ;; esac } delay="" case $1 in --delay) delay=$2 ; shift ; shift ;; *) ;; esac case $# in 2) ;; *) usage ;; esac device=$1 action=$2 case $action in on|off) ;; *) usage ;; esac find_device case "${controller}" in usb) find_hub ;; powerswitch) ;; *) echo "controller '${controller}' unknown" ; exit 1 ;; esac if [ -z $delay ] then do_switch else ( sleep $delay ; do_switch ) & fi