Skip to content

Instantly share code, notes, and snippets.

@dgoguerra
Forked from mnewt/proxy-toggle.sh
Last active September 7, 2023 02:55
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save dgoguerra/66d496345ee7e53169ad to your computer and use it in GitHub Desktop.
Save dgoguerra/66d496345ee7e53169ad to your computer and use it in GitHub Desktop.
Script to toggle Mac OS X SOCKS proxy, and setup a SOCKS server with SSH
#!/bin/sh
PROXY_INTERFACE="Wi-Fi"
PROXY_HOST=127.0.0.1
PROXY_PORT=1080
# A host where ssh can login without interaction, with a key-based
# authentication.
SOCKS_PROC_USER="username"
SOCKS_PROC_HOST="example.com"
SOCKS_PROC_IDENTITY="~/.ssh/id_rsa"
SOCKS_PROC_LOG=/tmp/ssh-socks-proxy-log.txt
SOCKS_PROC_PIDFILE=/tmp/ssh-socks-proxy-pid.txt
SOCKS_PROC_CMD="ssh -i $SOCKS_PROC_IDENTITY -t -t -D $PROXY_HOST:$PROXY_PORT $SOCKS_PROC_USER@$SOCKS_PROC_HOST"
if [[ $1 == "on" ]]; then
nohup $SOCKS_PROC_CMD > "$SOCKS_PROC_LOG" 2>&1 &
echo $! > "$SOCKS_PROC_PIDFILE"
sudo networksetup -setsocksfirewallproxy "$PROXY_INTERFACE" $PROXY_HOST $PROXY_PORT
echo "SOCKS proxy enabled"
elif [[ $1 == "off" ]]; then
sudo kill -9 $(cat "$SOCKS_PROC_PIDFILE")
rm "$SOCKS_PROC_PIDFILE"
sudo networksetup -setsocksfirewallproxystate "$PROXY_INTERFACE" off
echo "SOCKS proxy disabled"
elif [[ $1 == "status" ]]; then
echo "======================================================"
echo "Network Services:"
echo "======================================================"
networksetup -listallnetworkservices
echo
echo "======================================================"
echo "Current SOCKS Proxy Settings:"
echo "======================================================"
networksetup -getsocksfirewallproxy "$PROXY_INTERFACE"
echo
else
echo "`basename $0` toggles SOCKS proxy settings on OS X"
echo
echo "Usage: "
echo " $ proxy on # turns SOCKS proxy on"
echo " $ proxy off # turns SOCKS proxy off"
echo " $ proxy status # prints status of proxy settings"
echo
echo "proxy interface: " $PROXY_INTERFACE
echo "proxy host: " $PROXY_HOST
echo "proxy port: " $PROXY_PORT
echo
exit 65 # end process with error to indicate incorrect arguments
fi
@thmcmahon
Copy link

Worked great for me.

@jokuha
Copy link

jokuha commented Nov 23, 2017

Very nice indeed – thank you!

@jokuha
Copy link

jokuha commented Nov 25, 2017

Suggestions for improvement of the ssh command

  • remove the '-t's (not of any use AFAICT)
  • add an '-N' to indicate port forwarding

@hlwanghl
Copy link

Works well! Thanks a lot!

@deiga
Copy link

deiga commented Sep 22, 2018

Thanks very much for the inspiration for this.
I've modified the script a bit to make it configurable from the outside: https://github.com/deiga/dotfiles/blob/master/bin/proxy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment