Last active
March 25, 2016 16:22
-
-
Save mheiges/01d3c0d36f3ed68bda97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Throttle bandwidth on OS X Yosemite. Based on | |
# https://mop.koeln/blog/2015/06/01/Limiting-bandwidth-on-Mac-OS-X-yosemite/ | |
CMD_WITH_ARGS="$0 $*" | |
ANCHOR_NAME=custom_rules | |
while getopts :p:b: arg; do | |
case $arg in | |
p) | |
PORT=$OPTARG | |
;; | |
b) | |
BW=$OPTARG | |
;; | |
esac | |
shift $((OPTIND-1)) | |
done | |
: ${PORT:='80'} | |
: ${BW:='256kbit/s'} | |
restart_as_sudo() { | |
local run_as="root" | |
local cmd_with_args="$1" | |
if [ "$USER" != "$run_as" ]; then | |
prompt=$(cat <<EOF | |
sudo permissions are required to continue. | |
Enter your password: | |
EOF | |
) | |
exec sudo -u $run_as -H -P -p "$prompt" $cmd_with_args | |
exit ${?} # sice we're 'execing' above, we won't reach this exit | |
# unless something goes wrong. | |
fi | |
} | |
start() { | |
restart_as_sudo "$CMD_WITH_ARGS" | |
echo "Throttling Port ${PORT} to Bandwidth '${BW}'" | |
dnctl -fq flush | |
# Create a custom anchor in pf. This will reload your standard pf | |
# configuration plus a custom anchor named "custom_rules". We will | |
# place our custom rules there. | |
(cat /etc/pf.conf && | |
echo "dummynet-anchor \"${ANCHOR_NAME}\"" && | |
echo "anchor \"${ANCHOR_NAME}\"") | pfctl -f - 2>&1 | \ | |
grep -v ALTQ | \ | |
grep -v 'Use of -f option' | \ | |
grep -v 'present in the main' | \ | |
grep -v 'See /etc/pf.conf for further details' | \ | |
grep -v '^$' | |
# Pipe the desired traffic to dummynet. | |
cat <<EOF | pfctl -q -a ${ANCHOR_NAME} -f - 2>&1 | \ | |
grep -v ALTQ | \ | |
grep -v 'Use of -f option' | \ | |
grep -v 'present in the main' | \ | |
grep -v 'See /etc/pf.conf for further details' | \ | |
grep -v '^$' | |
dummynet in quick proto tcp from any port $PORT to any pipe 1 | |
EOF | |
dnctl pipe 1 config bw $BW | |
pfctl -E -q | |
} | |
stop() { | |
restart_as_sudo "$CMD_WITH_ARGS" | |
dnctl -f flush | |
pfctl -f /etc/pf.conf 2>&1 | \ | |
grep -v ALTQ | \ | |
grep -v 'Use of -f option' | \ | |
grep -v 'present in the main' | \ | |
grep -v 'See /etc/pf.conf for further details' | \ | |
grep -v '^$' | |
} | |
case "$1" in | |
start) | |
start | |
;; | |
stop) | |
stop | |
;; | |
restart) | |
stop | |
start | |
;; | |
*) | |
echo $"Usage: dummynet [-p PORT] [-b BANDWIDTH] {start|stop}" | |
echo "The default port is '${PORT}', default bandwidth is '${BW}'" | |
echo "'stop' resets firewall to defaults (-p, -b options are ignored)." | |
exit 1 | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment