Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Script to dynamically restrict the bandwidth of an ethernet host when
- # sharing the wifi internet connection.
- # See: http://markmaunder.com/2011/01/26/how-to-reliably-limit-the-amount-of-bandwidth-your-room-mate-or-bad-office-colleague-uses/
- if [ "$UID" != "0" ]
- then
- CMD=`which $0`
- sudo "$CMD"
- exit $?
- fi
- # Device we want to restrict
- BOX_IP=10.43.0.180
- HIGH_BW=2Gbit
- LOW_BW=500Kbit
- BANDWIDTH=${HIGH_BW}
- # Old systems use eth0/wlan0. Modern systems use those unpredictable enp0s31f6 and wlp0s20f3 names.
- ETH0=$(/sbin/ifconfig -a | grep '^enp' | sed 's/[: ].*$//' | head -n 1)
- ETH1=$(/sbin/ifconfig -a | grep '^enx' | sed 's/[: ].*$//' | head -n 1)
- WLAN0=$(/sbin/ifconfig -a | grep '^w' | sed 's/[: ].*$//' | head -n 1)
- # sh function to be used with trap
- ctrl_c() {
- # Delete old rules
- tc filter delete dev ${ETH1}
- exit 0
- }
- function manual() {
- read -e -p "Enter limit bandwidth in kbps (empty to exit): " -i "${BANDWIDTH}" BANDWIDTH
- if [ -z "${BANDWIDTH}" ]
- then
- tc qdisc del dev ${ETH1} root handle 1: cbq avpkt 1000 bandwidth 100mbit
- break
- fi
- if [[ "${BANDWIDTH}" =~ ^[0-9]*$ ]]
- then
- BANDWIDTH="${BANDWIDTH}kbit"
- fi
- }
- function auto() {
- if [ "${BANDWIDTH}" == "${HIGH_BW}" ]
- then
- BANDWIDTH="${LOW_BW}"
- else
- BANDWIDTH="${HIGH_BW}"
- fi
- read -e -p "Enter to change to ${BANDWIDTH}"
- }
- if [ "$(cat /proc/sys/net/ipv4/ip_forward)" != "1" ]
- then
- echo "Enable wifi -> ethernet Internet connection sharing before applying bandwidth limits"
- fi
- # Prepare for ^C
- trap ctrl_c INT
- # Delete old rules
- tc filter delete dev ${ETH1}
- tc qdisc add dev ${ETH1} root handle 1: cbq \
- avpkt 1000 bandwidth ${BANDWIDTH}
- tc class add dev ${ETH1} parent 1: classid 1:1 cbq \
- rate ${BANDWIDTH} allot 1500 prio 5 bounded isolated
- while true
- do
- BANDWIDTH="$(tc class list dev ${ETH1} parent 1: classid 1:1 | { read _ _ _ _ _ _ X _; echo $X; })"
- IP="$(tc -p filter list dev ${ETH1} parent 1: | grep src | { read _ _ _ X; echo $X; } | sed 's#/.*$##')"
- if [ -z "${IP}" ]
- then
- IP=${BOX_IP}
- tc filter add dev ${ETH1} parent 1: protocol ip \
- prio 16 u32 match ip dst ${IP} flowid 1:1
- tc filter add dev ${ETH1} parent 1: protocol ip \
- prio 16 u32 match ip src ${IP} flowid 1:1
- IP="$(tc -p filter list dev ${ETH1} parent 1: | grep src | { read _ _ _ X; echo $X; } | sed 's#/.*$##')"
- fi
- echo "Bandwidth: ${BANDWIDTH}"
- echo "Filtered IP: ${IP}"
- echo
- #manual
- auto
- tc class change dev ${ETH1} parent 1: classid 1:1 cbq \
- rate "${BANDWIDTH}" allot 1500 prio 5 bounded isolated
- done
- # Delete old rules
- tc filter delete dev ${ETH1}
- exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement