如何设置自动(重新)启动后台ssh隧道

时间:2022-06-03 02:10:04

I am a beginner user of linux, and also quite newbie at ssh and tunnels.

我是linux的初学者用户,也是ssh和隧道的新手。

Anyway, my goal is to maintain a ssh tunnel open in background.

无论如何,我的目标是在后台维护一个ssh隧道。

In order to do that, I wrote the following batch that I then added into crontab (the batch is automatically processed every 5 minutes during workdays and from 8am to 9pm). I read in some other thread in * that one should use autossh that will ensure the ssh will always be ok through a recurrent check. So did I....

为了做到这一点,我编写了以下批处理,然后将其添加到crontab中(批处理在工作日期间每隔5分钟自动处理一次,从早上8点到晚上9点)。我在*中的其他一些线程中读到,应该使用autossh来确保通过循环检查确保ssh始终正常。我也是....

#!/bin/bash
LOGFILE="/root/Tunnel/logBatchRestart.log"
NOW="$(date +%d/%m/%Y' - '%H:%M)" # date & time of log

if ! ps ax | grep ssh | grep tunnelToto &> /dev/null
then
    echo "[$NOW] ssh tunnel not running : restarting it" >> $LOGFILE
    autossh -f -N -L pppp:tunnelToto:nnnnn nom-prenom@193.xxx.yyy.zzz -p qqqq
    if ! ps ax | grep ssh | grep toto &> /dev/null
    then
            echo "[$NOW] failed starting tunnel" >> $LOGFILE
    else
            echo "[$NOW] restart successfull" >> $LOGFILE
    fi
fi

My problem is that sometimes the tunnel stops working, although every thing looks ok (ps ax | grep ssh > the result shows the two expected tasks : autossh main task and the ssh tunnel itself). I actually know about the problem cause the tunnel is used by a third party software that triggers an error as soon as the tunnel is no more responding.

我的问题是有时隧道停止工作,虽然每件事看起来都没问题(ps ax | grep ssh>结果显示了两个预期的任务:autossh主任务和ssh隧道本身)。我实际上知道这个问题导致隧道被第三方软件使用,一旦隧道不再响应就会触发错误。

SO I am wondering how I should improve my batch in order It will be able to check the tunnel and restart it if it happens to be dead. I saw some ideas in there, but it was concluded by the "autossh" hint... which I already use. Thus, I am out of ideas... If any of you have, I'd gladly have a look at them!

所以我想知道我应该如何改进我的批次顺序它将能够检查隧道并重新启动它,如果它真的死了。我在那里看到了一些想法,但它是由“autossh”提示结束的...我已经使用过了。因此,我没有想法......如果你有任何人,我很乐意看看他们!

Thanks for taking interest in my question, and for your (maybe) suggestions!

感谢您对我的问题和您(可能)的建议感兴趣!

3 个解决方案

#1


12  

Instead of checking the ssh process with ps you can do the following trick

您可以执行以下操作,而不是使用ps检查ssh进程

create script, that does the following and add it to your crontab via crontab -e

创建脚本,执行以下操作并通过crontab -e将其添加到crontab

#!/bin/sh

REMOTEUSER=username
REMOTEHOST=remotehost 

SSH_REMOTEPORT=22
SSH_LOCALPORT=10022

TUNNEL_REMOTEPORT=8080
TUNNEL_LOCALPORT=8080

createTunnel() {
    /usr/bin/ssh -f -N  -L$SSH_LOCALPORT:$REMOTEHOST:SSH_REMOTEPORT -L$TUNNEL_LOCALPORT:$REMOTEHOST:TUNNEL_REMOTEPORT $REMOTEUSER@$REMOTEHOST
    if [[ $? -eq 0 ]]; then
        echo Tunnel to $REMOTEHOST created successfully
    else
        echo An error occurred creating a tunnel to $REMOTEHOST RC was $?
    fi
}

## Run the 'ls' command remotely.  If it returns non-zero, then create a new connection
/usr/bin/ssh -p $SSH_LOCALPORT $REMOTEUSER@localhost ls >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo Creating new tunnel connection
    createTunnel
fi

In fact, this script will open two ports

实际上,这个脚本将打开两个端口

  • port 22 which will be used to check if the tunnel is still alive
  • 端口22将用于检查隧道是否仍然存活

  • port 8080 which is the port you might want to use
  • 端口8080,这是您可能想要使用的端口

Please check and send me further questions via comments

请通过评论检查并向我发送更多问题

#2


0  

(I add this as an answer since there is not enough room for it un a comment)

(我添加这个作为答案,因为没有足够的空间来发表评论)

Ok, I managed to make the batch run to launch the ssh tunnel (I had to specify my hostname instead of localhost in order it could be triggered) :

好吧,我设法让批处理运行以启动ssh隧道(我必须指定我的主机名而不是localhost,以便它可以被触发):

#!/bin/bash

LOGFILE="/root/Tunnel/logBatchRedemarrage.log"
NOW="$(date +%d/%m/%Y' - '%H:%M)" # date et heure du log


REMOTEUSER=username
REMOTEHOST=remoteHost

SSH_REMOTEPORT=22
SSH_LOCALPORT=10022

TUNNEL_REMOTEPORT=12081
TUNNEL_SPECIFIC_REMOTE_PORT=22223
TUNNEL_LOCALPORT=8082

createTunnel() {
    /usr/bin/ssh -f -N  -L$SSH_LOCALPORT:$REMOTEHOST:$SSH_REMOTEPORT -L$TUNNEL_LOCALPORT:$REMOTEHOST:$TUNNEL_REMOTEPORT $REMOTEUSER@193.abc.def.ghi -p $TUNNEL_SPECIFIC_REMOTE_PORT
    if [[ $? -eq 0 ]]; then
        echo [$NOW] Tunnel to $REMOTEHOST created successfully >> $LOGFILE
    else
        echo [$NOW] An error occurred creating a tunnel to $REMOTEHOST RC was $? >> $LOGFILE
    fi
    }

## Run the 'ls' command remotely.  If it returns non-zero, then create a new connection
/usr/bin/ssh -p $SSH_LOCALPORT $REMOTEUSER@193.abc.def.ghi ls >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo [$NOW] Creating new tunnel connection >> $LOGFILE
    createTunnel
fi

However, I got some immediate message (below) when the tunnel is running and when cron tries to lauch the batch again... sounds like it cannot listen to it. Also since I need some time to get a proof , I can't say yet it will successfully restart if the tunnel is out.

但是,当隧道运行时,当cron再次尝试重新启动批处理时,我得到了一些即时消息(下面)......听起来它听不到它。此外,由于我需要一些时间来获得证据,我不能说如果隧道出来它会成功重启。

Here's the response to the second start of the batch.

这是批次第二次启动的响应。

bind: Address already in use channel_setup_fwd_listener: cannot listen to port: 10022 bind: Address already in use channel_setup_fwd_listener: cannot listen to port: 8082 Could not request local forwarding.

bind:地址已经在使用channel_setup_fwd_listener:无法侦听端口:10022 bind:地址已经在使用channel_setup_fwd_listener:无法侦听端口:8082无法请求本地转发。

#3


-1  

You can use netcat to test the connection and open it if necessary:

您可以使用netcat测试连接并在必要时打开它:

while sleep 3; do nc -z localhost 3333 >/dev/null || ssh -NfL 3333:lg:5432 rene@lg; done

#1


12  

Instead of checking the ssh process with ps you can do the following trick

您可以执行以下操作,而不是使用ps检查ssh进程

create script, that does the following and add it to your crontab via crontab -e

创建脚本,执行以下操作并通过crontab -e将其添加到crontab

#!/bin/sh

REMOTEUSER=username
REMOTEHOST=remotehost 

SSH_REMOTEPORT=22
SSH_LOCALPORT=10022

TUNNEL_REMOTEPORT=8080
TUNNEL_LOCALPORT=8080

createTunnel() {
    /usr/bin/ssh -f -N  -L$SSH_LOCALPORT:$REMOTEHOST:SSH_REMOTEPORT -L$TUNNEL_LOCALPORT:$REMOTEHOST:TUNNEL_REMOTEPORT $REMOTEUSER@$REMOTEHOST
    if [[ $? -eq 0 ]]; then
        echo Tunnel to $REMOTEHOST created successfully
    else
        echo An error occurred creating a tunnel to $REMOTEHOST RC was $?
    fi
}

## Run the 'ls' command remotely.  If it returns non-zero, then create a new connection
/usr/bin/ssh -p $SSH_LOCALPORT $REMOTEUSER@localhost ls >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo Creating new tunnel connection
    createTunnel
fi

In fact, this script will open two ports

实际上,这个脚本将打开两个端口

  • port 22 which will be used to check if the tunnel is still alive
  • 端口22将用于检查隧道是否仍然存活

  • port 8080 which is the port you might want to use
  • 端口8080,这是您可能想要使用的端口

Please check and send me further questions via comments

请通过评论检查并向我发送更多问题

#2


0  

(I add this as an answer since there is not enough room for it un a comment)

(我添加这个作为答案,因为没有足够的空间来发表评论)

Ok, I managed to make the batch run to launch the ssh tunnel (I had to specify my hostname instead of localhost in order it could be triggered) :

好吧,我设法让批处理运行以启动ssh隧道(我必须指定我的主机名而不是localhost,以便它可以被触发):

#!/bin/bash

LOGFILE="/root/Tunnel/logBatchRedemarrage.log"
NOW="$(date +%d/%m/%Y' - '%H:%M)" # date et heure du log


REMOTEUSER=username
REMOTEHOST=remoteHost

SSH_REMOTEPORT=22
SSH_LOCALPORT=10022

TUNNEL_REMOTEPORT=12081
TUNNEL_SPECIFIC_REMOTE_PORT=22223
TUNNEL_LOCALPORT=8082

createTunnel() {
    /usr/bin/ssh -f -N  -L$SSH_LOCALPORT:$REMOTEHOST:$SSH_REMOTEPORT -L$TUNNEL_LOCALPORT:$REMOTEHOST:$TUNNEL_REMOTEPORT $REMOTEUSER@193.abc.def.ghi -p $TUNNEL_SPECIFIC_REMOTE_PORT
    if [[ $? -eq 0 ]]; then
        echo [$NOW] Tunnel to $REMOTEHOST created successfully >> $LOGFILE
    else
        echo [$NOW] An error occurred creating a tunnel to $REMOTEHOST RC was $? >> $LOGFILE
    fi
    }

## Run the 'ls' command remotely.  If it returns non-zero, then create a new connection
/usr/bin/ssh -p $SSH_LOCALPORT $REMOTEUSER@193.abc.def.ghi ls >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
    echo [$NOW] Creating new tunnel connection >> $LOGFILE
    createTunnel
fi

However, I got some immediate message (below) when the tunnel is running and when cron tries to lauch the batch again... sounds like it cannot listen to it. Also since I need some time to get a proof , I can't say yet it will successfully restart if the tunnel is out.

但是,当隧道运行时,当cron再次尝试重新启动批处理时,我得到了一些即时消息(下面)......听起来它听不到它。此外,由于我需要一些时间来获得证据,我不能说如果隧道出来它会成功重启。

Here's the response to the second start of the batch.

这是批次第二次启动的响应。

bind: Address already in use channel_setup_fwd_listener: cannot listen to port: 10022 bind: Address already in use channel_setup_fwd_listener: cannot listen to port: 8082 Could not request local forwarding.

bind:地址已经在使用channel_setup_fwd_listener:无法侦听端口:10022 bind:地址已经在使用channel_setup_fwd_listener:无法侦听端口:8082无法请求本地转发。

#3


-1  

You can use netcat to test the connection and open it if necessary:

您可以使用netcat测试连接并在必要时打开它:

while sleep 3; do nc -z localhost 3333 >/dev/null || ssh -NfL 3333:lg:5432 rene@lg; done