Last active
October 20, 2022 04:16
-
-
Save lncan/d47a622e88208ca3fb9cd962b27fa2a0 to your computer and use it in GitHub Desktop.
SSH tunnel for Docker process
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/zsh | |
function sdocker() { | |
E_RED='\033[0;31m' | |
E_GREEN='\033[0;32m' | |
E_YELLOW='\033[1;33m' | |
E_NORMAL='\033[0m' | |
function prinfo() { | |
echo "${E_GREEN}=i=${E_NORMAL} $*" | |
} | |
function prerror() { | |
echo "${E_RED}/e/${E_NORMAL} $*" | |
} | |
function prwarn() { | |
echo "${E_YELLOW}/!/${E_NORMAL} $*" | |
} | |
function get_unused_port() { | |
for port in $(seq 2780 2800); | |
do | |
echo -ne "\035" | nc 127.0.0.1 $port > /dev/null 2>&1; | |
[ $? -eq 1 ] && echo "$port" && break; | |
done | |
} | |
if [ -z "$DOCKER_HOST_NAME" ]; then | |
prinfo "No existing connection. Proceeding ..." | |
else | |
prwarn "Shell already connected to $DOCKER_HOST_NAME" | |
exit 1 | |
fi | |
SOCKET_DIR=/tmp/x-ssh-docker | |
SOCKET_PATH=$SOCKET_DIR/$1-conn.sock | |
SERVER=$1 | |
DOCKER_PORT="$(get_unused_port)" | |
[ -z "$SERVER" ] && \ | |
prinfo "Usage: x-ssh-docker <server>" && \ | |
exit 1 | |
[ -S "$SOCKET_PATH" ] && \ | |
prerror "Connection already exists." && \ | |
prerror "Terminate connection command:" && \ | |
prinfo "ssh -S $SOCKET_PATH -O exit $SERVER" && \ | |
exit 1 | |
mkdir -p $SOCKET_DIR | |
prinfo "Establishing background SSH connection tunnel to $SERVER ..." | |
ssh -fNM -S $SOCKET_PATH -L $DOCKER_PORT:/var/run/docker.sock $SERVER | |
if [ $? -eq 0 ]; then | |
prinfo "Tunnel connected. Docker exposed via DOCKER_HOST=localhost:$DOCKER_PORT. Starting shell ..." | |
DOCKER_HOST_NAME=$SERVER DOCKER_HOST=:$DOCKER_PORT /usr/local/bin/zsh | |
ssh -S $SOCKET_PATH -O exit $SERVER | |
prinfo "Session completed. Closed connection to $SERVER." | |
else | |
prerror "Unable to setup tunnel." | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment