How to terminate ssh tunnel child process after bash script exits

I have a bash script that creates an ssh tunnel to securely connect a remote mysql server, as shown below.

ssh -f -N -L  $LOCAL_PORT:localhost:3306 $REMOTE_USER@$REMOTE_IP
mysql -P $LOCAL_PORT -h 127.0.0.1 -u lapl_stg -p${REMOTE_DB_PASS} < ./t1.sql > ./out.txt

After opening the ssh tunnel in the bash script, after exiting the bash script, I noticed that the ssh tunnel child process is still alive.

After the script exits, if you execute netstat, this is shown below.

netstat -a -n -p -l
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name

tcp        0      0 127.0.0.1:3308          0.0.0.0:*               LISTEN      6402/ssh        
tcp        0      0 10.44.44.11:46836       10.44.44.21:22          ESTABLISHED 6402/ssh        
tcp6       0      0 ::1:3308                :::*                    LISTEN      6402/ssh   

How do you end the ssh child (6402) process elegantly to clear in a script? I was thinking about using killall ssh, but it could accidentally kill other ssh processes created by others.

Thank.

+5
source share
1 answer

I found a way to do this using control sockets in SSH. Primarily:

ssh  -M -f -N -L  $LOCAL_PORT:localhost:3306 $REMOTE_USER@$REMOTE_IP -S /tmp/ssh-control
mysql -P $LOCAL_PORT -h 127.0.0.1 -u lapl_stg -p${REMOTE_DB_PASS} < ./t1.sql > ./out.txt
ssh -S /tmp/ssh-control -O exit $REMOTE_IP

, script, , -f, ssh, . SSH .

+7

All Articles