Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to terminate ssh tunnel child process upon bash script exit

I have a bash script that creates ssh tunnel to connect remote mysql server securely 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, upon exit of the bash script, I noticed that the ssh tunnel child process is still alive.

After the script exits, if you do netstat, it shows 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 terminate the ssh child process(6402) elegantly to clean up in the script? I thought about using 'killall ssh' but it could kill other ssh processes created by others by accident.

Thank you.

like image 797
user1026669 Avatar asked Mar 05 '13 23:03

user1026669


1 Answers

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

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

The reason why the process doesn't get killed at script exit is that -f passed to ssh forks it to the background. This is needed for SSH tunnels to work without interrupting the execution of the next line.

like image 165
cwgem Avatar answered Nov 16 '22 13:11

cwgem