Wednesday 15 June 2011

Managing Deluge Daemon

I use Deluge bit torrent client on a couple of headless machines. There's not much to it, you can learn how to set it up here

However up until now I've been manually bringing it up and down at the command line, it's not hard but I thought I'd streamline it a bit by making a script.

Download or copy+paste this script into a file called "torrents" and make it executable;

#!/bin/bash

FLAG="/tmp/torrents_on"
UPDATE_FIREWALL="/store/scripts/firewall"

# Checking for dependancies
if [ ! ${DELUGED=`which deluged`} ] ; then echo "ERROR : Can't find 'deluged' on your system, aborting" ; exit 1; fi
if [ ! ${DELUGE_WEB=`which deluge-web`} ] ; then echo "ERROR : Can't find 'deluge-web' on your system, web interface will be disabled" ; exit 1; fi

DELUGED_PID=`ps ax | grep "${DELUGED}" | grep -v grep | awk '{print $1}'`
if [ "${DELUGED_PID}" = "" ] ; then DELUGED_PID=0 ; fi

DELUGE_WEB_PID=`ps ax | grep "${DELUGE_WEB}" | grep -v grep | awk '{print $1}'`
if [ "${DELUGE_WEB_PID}" = "" ] ; then DELUGE_WEB_PID=0 ; fi

case "$1" in
start)
if [ ! $DELUGED_PID -gt "0" ] ; then
deluged
nohup deluge-web > /dev/null 2>&1 &
touch $FLAG
$UPDATE_FIREWALL
exit 0
else
echo "Deluged is already running (PID $DELUGED_PID)"
exit 1
fi
;;

stop)
if [ ! $DELUGED_PID = "0" ] ; then
kill $DELUGED_PID
kill $DELUGE_WEB_PID
rm $FLAG
$UPDATE_FIREWALL
exit 0
else
echo "Deluged is not running"
exit 1
fi
;;

status)
if [ $DELUGED_PID -gt "0" ] ; then
ps ax | grep deluge | grep -v grep
exit 0
else
echo "Deluged is not running"
exit 0
fi
;;

*)
echo "Usage: torrents {start|stop|status}"
exit 1
;;
esac


The script will open/close ports on your firewall as required assuming you modify the UPDATE_FIREWALL variable with the correct location of your firewall script and modify that script to include something like this;
# Flush tables before re-applying ruleset
sudo /sbin/iptables --flush

# Bittorrent traffic
if [ -f /tmp/torrents_on ] ; then
sudo /sbin/iptables -A INPUT -p tcp --dport 58261 -j ACCEPT
sudo /sbin/iptables -A INPUT -p udp --dport 58261 -j ACCEPT
fi

#

# Drop all other traffic from WAN
sudo /sbin/iptables -A INPUT -i $WAN -j DROP
sudo /sbin/iptables -A FORWARD -i $WAN -j DROP

The above firewall script is for illustraion purposes and shouldn't be used as is. Make sure you modify use a script that suits your own network.

Once installed, you can now use the script to control deluged and the deluge web interface from the command line using this syntax;

torrents {start|stop|status}

Enjoy!

2 comments:

John Tells All said...

The bit about killing old "deluge" processes can be shortened to one line:

pkill deluge

pkill/pgrep are awesome. "Lsof" is also really powerful, alas also quite inscrutable.

Brett said...

Thanks John, I could also use killall but since I already had the PID for the process then I figured I would explicitly kill it. I will check out pkill though, looks interesting.