Skip to content

Instantly share code, notes, and snippets.

@feihong
Last active September 29, 2015 23:05
Show Gist options
  • Save feihong/3ec6de7f2e70b78c5a30 to your computer and use it in GitHub Desktop.
Save feihong/3ec6de7f2e70b78c5a30 to your computer and use it in GitHub Desktop.
Python script for SSH tunneling on Mac OS X

Creating and configuring a DigitalOcean droplet for SSH tunneling

Creating the droplet on DigitalOcean

  1. Click Create Droplet
  2. Name it 'tunnel'
  3. Select $5/mo
  4. Select Singapore
  5. Select Ubuntu 14.04
  6. Add your SSH key (probably already there if you've created other droplets)

Adding your user

adduser username
visudo

Add this line: username ALL=(ALL:ALL) ALL

cd /home/username
mkdir .ssh
cd /home/fhsu/
mkdir .ssh
cd .ssh
nano authorized_keys   # copy in the keys
chmod 600 authorized_keys
chown username:username authorized_keys

Remember that you can always reset your root password in the control panel.

#!/usr/bin/env python
"""
A simple program for starting a SOCKS proxy and configuring your Mac OS X system
settings to use it by default.
Usage:
tunnel.py 128.123.123.12 22 wifi
Source: http://pixelsvsbytes.com/blog/2011/09/easy-ssh-tunnelling-for-the-mac/
"""
import argparse
from subprocess import Popen, call, check_output
def tunnel(ip_addr, port, service):
service = {
'wifi': 'Wi-Fi',
'ethernet': 'Ethernet',
}[service]
# Establish the SSH tunnel.
cmd = [
'ssh',
'-D', port,
'-N', # no interactive shell
'-C', # compression
ip_addr,
]
proc = Popen(cmd)
# Set socks proxy parameters.
cmd = ['networksetup', '-setsocksfirewallproxy', service, '127.0.0.1', port,
'off']
run(cmd)
# Turn on socks proxy.
cmd = ['networksetup', '-setsocksfirewallproxystate', service, 'on']
run(cmd)
# Show the IP address after tunneling. Note that curl won't use the proxy
# by default.
cmd = ['curl', '-s', '--proxy', 'socks5://127.0.0.1:' + port,
'http://ipecho.net/plain']
result = check_output(cmd)
print 'Your IP address is now ' + result
raw_input('Press any key to shut off socks proxy')
# Turn off socks proxy.
cmd = ['networksetup', '-setsocksfirewallproxystate', service, 'off']
run(cmd)
# Shut down the tunnel.
proc.kill()
def run(cmd):
print ' '.join(cmd)
call(cmd)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Set up an SSH tunnel.')
parser.add_argument('ip_address',
help='The IP address of the virtual private server')
parser.add_argument('port',
help='The port number of the SSH tunnel process')
parser.add_argument('service', default='wifi',
help='The service you want to tunnel (wifi|ethernet)')
args = parser.parse_args()
tunnel(args.ip_address, args.port, args.service)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment