Mastering ssh-tunnels


Add this to ~/.zshrc or ~/.bashrc and be happy =):

# By saying PROXY I mean it is a host located in internal network.
# You can access any other internal hosts from it via SSH.

# Export some variables
export PROXY_KEY_PATH="~/.ssh/proxy/id_rsa" # path to locally stored private key from PROXY-server
export PROXY_USER="user" # user name to get access to PROXY via SSH
export PROXY_HOST="" # FQDN or IP of a proxy
export PROXY_AUTH="$PROXY_USER@$PROXY_HOST" # literally it is a string ""

# Connect to PROXY via SSH
alias proxy="ssh $PROXY_AUTH"

# Connect to PROXY via SSH and attach to screen (P.S. don't do it inside a locally launched screen :))
alias proxy_screen="ssh -t $PROXY_AUTH screen -x"

# Forward some service's port which you can access only from PROXY to localhost:1234
# 1234 - local port with service
# ServiceHost - IP-address of a host with service
# ServicePort - Port of a service at ServiceHost
alias tunnel_service='ssh -L 1234:ServiceHost:ServicePort $PROXY_AUTH'

# Forward MySQL-connection which you can access only from some host inside enterprise network (no a PROXY-host) to localhost
# MySQLHost - IP-address of MySQL-server
# WebHost - IP-address of a host that can connect to MySQLHost
# WebUser - User name to access from PROXY to WebHost via SSH
alias tunnel_mysql='ssh -A -i $PROXY_KEY_PATH -L 3306:MySQLHost:3306 -o ProxyCommand="ssh $PROXY_AUTH nc WebHost 22" WebUser@WebHost'

# Run some command at remote server and disconnect
# TargetHost -IP-address of a host where you wanna execute your command
# TargetUser - User name to access from PROXY to TargetHost via SSH
# 'cd /srv/some/directory/; ls -al | wc -l)' - the command you are willing to run
alias remote_directory_count="ssh -i $PROXY_KEY_PATH -t -o ProxyCommand='ssh $PROXY_AUTH nc TargetHost 22' TargetUser@TargetHost 'cd /srv/some/directory/; ls -al | wc -l)'"