~drscream

SSH SOCKS proxy via MacOS X launchctl

I use an SOCKS proxy to connect to some services in different networks. For that reason I use a simple SSH SOCKS proxy solution which makes it really easy:

ssh -f -N -D7070 gateway.example.com

But running this command every time when I switch my location or the laptop hibernated is not really convenient. MacOS X provides launchctl as a service manager, so why not using it?

Agents running for the current user are stored in ~/Library/LaunchAgents/ as an XML based plist file. I named my file like the host I’m using to connect to, so it’s com.example.gateway.socks-tunnel.plist.

My file looks like the following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
	<dict>
		<key>LimitLoadToSessionType</key>
		<string>Aqua</string>
		<key>OnDemand</key>
		<false/>
        <key>Label</key>
        <string>com.example.gateway.socks-tunnel</string>
        <key>ProgramArguments</key>
        <array>
            <string>/usr/bin/ssh</string>
            <string>-D7070</string>
            <string>-N</string>
            <string>-n</string>
            <string>-C</string>
            <string>-o ControlMaster=no</string>
            <string>gateway.example.com</string>
        </array>
        <key>StandardErrorPath</key>
        <string>/tmp/com.example.gateway.socks-tunnel.log</string>
    </dict>
</plist>

If you’re using ControlMaster ssh settings you should disable it for the tunnel setup via -o ControlMaster=no. For the first time it requires to load the plist file:

launchctl load ~/Library/LaunchAgents/com.example.gateway.socks-tunnel.plist

Send your comment by mail.