简体   繁体   中英

Bash script - How to run ssh after another one is connected

I don't have a powerful hardware so I can't run multiple ssh tunnels at the same time or it'll make the CPU load go way too high, my goal is to run a ssh tunnel after another one is connected, and reconnect if one of my ssh gets disconnected, so basically it's like this:

while true; do
if (1st ssh isn't connected); then
   connect the first ssh
elif (1st ssh is finally connected); then
   run the second ssh
elif (2nd ssh is finally connected); then
   run the 3rd ssh
fi
sleep 1
done

The problem is that the amount of ssh tunnels keeps changing, sometimes a user wants to run 3 ssh tunnels and sometimes 5, it looks like this to run the script:

mytunnel.sh -a [number of tunnels they wanna run]

I'm thinking of for loop but I just can't figure out how to write it inside a for loop . Please help me.

Here is a for loop you can use:

#!/usr/local/bin/bash

LOOP=$1
for (( c=1; c<=$LOOP; c++ ))
do
      echo "$c "
done

Replace echo with your commands and LOOP with whatever command-line arg you'll be using. This example reads command-line arg 1 (ie $1).

Example execution:

在此处输入图片说明

Tricky. Unfortunately I don't think ssh returns anything when it connects a tunnel, nor does it exit immediately when the connection is broken.

Instead what you probably want to do is make a port monitor that periodically checks that the port is accepting connections and spawns a new ssh tunnel (possibly killing the old ssh process) if it isn't.

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