简体   繁体   中英

Automatically establish ssh-tunnel, wait until ssh-tunnel is established, then establish normal VPN connection

I got this script:

#!/usr/bin/env bash

if [ ! "$UID" = 0 ]; then
    if [ `type -P gksu` ]; then
        SUDOAPP="gksu"
    elif [ `type -P kdesu` ]; then
        SUDOAPP="kdesu"
    else
        SUDOAPP="sudo"
    fi
fi

if [ -n "$1" ]; then
    if [ "$1" = "start" ]; then
        $SUDOAPP systemctl start openvpn@******
    elif [ "$1" = "stop" ]; then
        $SUDOAPP systemctl stop openvpn@******
    elif [ "$1" = "restart" ]; then
        $SUDOAPP systemctl restart openvpn@******
    else
        echo "Invalid command"
        exit 1
    fi
else
    echo "Run 'start', 'stop' or 'restart' as an argument to start, stop or restart the ******"
    exit 1
fi

It works fine. However I also need to establish the ssh tunnel. - Before openvpn connects to my VPN. I've got a script which does precisely that:

#!/bin/bash
# --------------------------------------------------------
# ******* | https://******.org | ****************************************
# SSH Client Configuration, Linux/OSX
# ******_*************
# --------------------------------------------------------

chmod 600 /etc/openvpn/sshtunnel.key
while :
do
echo ""; echo "****** SSH Tunnel"
ssh -i /etc/openvpn/sshtunnel.key -L ****:127.0.0.1:**** sshtunnel@**.**.**.* -p ** -N -T -v
read -t 5 -p "Retry? (or wait 5 sec for Y)" yn
if [[ $yn == "n" || $yn == "N" ]]; then break; fi
done

How do I add this to the first script in a way as to make the openvpn part wait until the ssh client is fired up?

The first script can loop checking the tunnel until it succeeds. You can use nc (netcat) to do that and capture the output in a shell variable:

while [[ -z "$nc_output" ]]; do
  read -r nc_output < <(nc -v -d -u localhost openvpn 2>&1)
  sleep 2
done

This checks every 2 seconds whether UDP port "openvpn" (substitute what you're actually tunnelling) can be connected to, relying on the -v option to output text if it succeeds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM