Automating BitTorrent traffic detection via bash

Hi all,

Earlier today, I read an article on how to detect BitTorrent traffic using tshark (the cli version of Wireshark).

I wanted to have a go at creating a simple script, that when BitTorrent packets are detected the network connection will be throttled. The thing is that I am not great at bash scripting and would like some assistance with my script (see below).

#!/bin/bash
# Sample network stream for 10 seconds and filter for uTP and/or BitTorrent traffic that does not originate on port 80 (HTTP), 443 (HTTPS), 22 (SSH)
TSOUTPUT=$(sudo tshark -a "duration:10" -Y 'udp[8:5] == "\x64\x32\x3A\x69\x70" or bittorrent' -f 'not port 80 and not port 22 and not port 443')

# Get the output of running the tshark command
if [[ $TSOUTPUT != "0 packets captured" ]] then
	# BitTorrent detected - slow down upload/download speed to 0.5 Mbps
	wondershaper eth0 512 512
else
	# Not BitTorrent detected - reset any previously throttled speeds back to full speed
	wondershaper clear eth0
fi

The bash script should be designed to run in cron every minute or two.

I really would appreciate any help with this.

I'm not really familiar with tshark or wondershaper so I've commented them and replaced with a testing string that you can edit/test to get the functionality of your bash script proven.

Have a play around with this (you should be able to run it directly from a bash login):

#!/bin/bash
# Sample network stream for 10 seconds and filter for uTP and/or BitTorrent traffic that does not originate on port 80 (HTTP), 443 (HTTPS), 22 (SSH)
# TSOUTPUT=$(sudo tshark -a "duration:10" -Y 'udp[8:5] == "\x64\x32\x3A\x69\x70" or bittorrent' -f 'not port 80 and not port 22 and not port 443')
TSOUTPUT="some random output

Result: 10 packets captured
done"

# Get the output of running the tshark command
if [[ $TSOUTPUT =~ " 0 packets captured" ]]
then
        # No BitTorrent detected - reset any previously throttled speeds back to full speed
        #wondershaper clear eth0
    echo "None Found - unshape"
else
        # BitTorrent detected - slow down upload/download speed to 0.5 Mbps
        # wondershaper eth0 512 512
    echo "Found traffic - shape connection now"
fi