Python script for SSH tunneling on Mac OS X
This short script makes it to easy to start a SOCKS proxy and then configure the entire system to use it. This means that GUI programs like your web browsers will use the proxy without any additional configuration on your part. You can kill the SOCKS proxy by pressing ENTER, which will also turn off the system-wide proxying.
#!/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. 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)











