juslintek
juslintek

Reputation: 511

How to forward socat command to ssh target server via ssh tunnel?

I am currently using sequence of commands such as:

  1. ssh -N -L 3307:localhost:3307 [email protected]
  2. inside open terminal I run this: socat TCP-LISTEN:3307,reuseaddr,fork UNIX-CONNECT:/var/lib/mysql/mysql.sock

How can I make it as an ssh command, problem is that I am prohibited at using password, no ~/.ssh/authorized_keys work. I guess password only access is enforced over at /etc/ssh/sshd_config.

Anyway, how can I make this work, when I add to my profile functions like this:

start_db_proxy() {
  if [[ -n "$SSH_TUNNEL_PID" && -n "$(ps -p $SSH_TUNNEL_PID -o pid=)" ]]; then
    echo "Proxy is already running with PID $SSH_TUNNEL_PID."
    return
  fi

  echo "Starting SSH tunnel and socat on the remote machine..."

  # Start the SSH tunnel in the background and Start socat on the remote machine via SSH
  ssh -N -L 3307:localhost:3307 [email protected] "socat TCP-LISTEN:3307,reuseaddr,fork UNIX-CONNECT:/var/lib/mysql/mysql.sock" &
  SSH_TUNNEL_PID=$!

  # Wait for the SSH tunnel to be established
  sleep 2

  # Save the PIDs to environment variables
  export SSH_TUNNEL_PID

  echo "Proxy started with mysql socket forwarding via ssh $SSH_TUNNEL_PID."
}

# Function to stop the SSH tunnel and socat
stop_db_proxy() {
  if [[ -n "$SSH_TUNNEL_PID" ]]; then
    kill $SSH_TUNNEL_PID 2>/dev/null
    unset SSH_TUNNEL_PID
    echo "Killed SSH tunnel."
  fi
}

# Ensure cleanup when the terminal session exits
trap stop_ironwall_db_proxy EXIT

due to not prompting for password and getting suspended with prompt for password. What would be the correct approach in getting the prompt and putting it to background?

Upvotes: 2

Views: 123

Answers (0)

Related Questions