DEV Community

manuel
manuel

Posted on • Originally published at wildauer.io on

How to use ssh as a socks5 proxy with autossh

To randomize my ssh tunnels, I use a small script. This script looks at my ~/.ssh/config for hosts with the comment #socks5 after the Host and picks one out. I use autossh to maintain the connection.

AUTOSSH(1): autossh is a program to start a copy of ssh and monitor it, restarting it as necessary should it die or stop passing traffic.

#!/bin/bash

# ssh user config (http://www.openbsd.org/cgi-bin/man.cgi?query=ssh_config)
SSH_CONFIG=~/.ssh/config

# local port
PORT=8888

# export pid to file
export AUTOSSH_PIDFILE=/tmp/proxy.pid

# array with hosts from SSH_CONFIG.
# append "#socks5" at the end of the Host line.
# Example: "Host yourHost #socks5"
eval HOSTS=( $(awk '/^Host(.*?)#socks5$/ {print $2}' ${SSH_CONFIG}) )
N=1
for index in `shuf --input-range=0-$(( ${#HOSTS[*]} - 1 )) | head -${N}`
do
        echo -en "Host: ${HOSTS[$index]} Port: ${PORT}\n"
        # using autossh - Automatically restart SSH sessions and tunnels
        AUTOSSH_DEBUG=1
        AUTOSSH_GATETIME=0
        autossh -M 20000 -N -D ${PORT} ${HOSTS[$index]}
done
Enter fullscreen mode Exit fullscreen mode

I start the script automatic on boot with Supervisor

/etc/supervisor.d/proxy.ini:

command=/path/to/proxy.sh
autostart=true
autorestart=true
startretries=3
user=YOURUSERNAME
stderr_logfile=/var/log/proxy.log
stdout_logfile=/var/log/proxy.log
Enter fullscreen mode Exit fullscreen mode

Now you can set 127.0.0.1:8888 as a proxy when your application support SOCKS5

Top comments (0)