'How to close ssh connections opened via script

I use the following script to open a ssh tunnel to a bunch servers always varying between mysql, redis and ssh ports. I am doing this while being in the company vpn, but I had the same problem back in the days, when you worked in the office.

Usually I start the script and use the opened connection with other tools like SequelPro or PhpStorm to connect to webserver or databases. Ideally it would just run until I don't need it any more and then I would exit the jumpserver and the connections should close. That is fine as long as I don't loose the connection and get kicked out of the jumpserver.

#!/bin/sh

username="my-user"
jumpServer="my.bastionserver.net"
hosts=("my.awsserver1.com" "my.awsserver2.com" "my.awsserver3.com")

destMysqlPort=3306
destSshPort=22
destRedisPort=6379

x=10001
y=10002
z=10003

for i in "${hosts[@]}"; do
  :
  server=$i
  sshTunnel="$sshTunnel -L $x:$server:$destMysqlPort -L $y:$server:$destSshPort -L $y:$server:$destRedisPort"
  echo "Server: $server -- MYSQL: $x -- SSH: $y-- Redis: $z"
  x=$((x + 3))
  y=$((y + 3))
  z=$((z + 3))
done

if [ -z "$sshTunnel" ]
then
  echo "ssh tunnels are empty"
else
  ssh $sshTunnel $username@$jumpServer -i ~/.ssh/aws
fi

the output is as follows:

$ ./awstunnel.sh
Server: my.awsserver1.com -- MYSQL: 10001 -- SSH: 10002-- Redis: 10003
Server: my.awsserver1.com -- MYSQL: 10004 -- SSH: 10005-- Redis: 10006
Server: my.awsserver1.com -- MYSQL: 10007 -- SSH: 10008-- Redis: 10009
[...]

When I try to connect again via this script I get the messages that the address is already in use:

bind [127.0.0.1]:10002: Address already in use
channel_setup_fwd_listener_tcpip: cannot listen to port: 10002
bind [127.0.0.1]:10005: Address already in use
channel_setup_fwd_listener_tcpip: cannot listen to port: 10005
[...]

How can I change the script so that I can start it again right away and don't have to wait for quite some time until the connection via this tunnel really closes?

I work from a Mac and the jumpserver is a Linux server, where I should not change settings.



Solution 1:[1]

Just like this, a little hint:

To get the PID of the last executed command you have to type:

echo "$!"

So, what you can do is just store the PID after each ssh login command like this for example:

#Store the pid of the last command in a variable named sshPid: 
sshPid=$!

and when you are done just kill the corresponding PID with:

kill ${sshPid}

Tell me if that worked for you :p

Bguess

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bguess