I've a question about SSH reverse tunnel.
I've an Ubuntu server with sshd installed.
I open an SSH reverse tunnel from a remote machine. On that machine the connection is restarted every time the tunnel is interrupted.
Whenever a tunnel is opened, on the SSH server I can see two connections when I am using netstat
. One connection is listening to the internal server port. The other is listening on an external port. The latter one is the SSH tunnel.
As example:
given 203.0.113.10: my SSH server and 10.34.23.12 my remote PC, 5000 the port on my remote PC i would like to access to
ssh -R 1122:localhost:5000 [email protected]
Now server side I've two listening connections, which looks like this
tcp6 0 :::1122 :::* LISTEN
tcp6 0 0 203.0.113.10:22 10.34.23.12:62734 ESTABLISHED
I use/run the nc
command from the server, to check for the tunnel to work
nc -z -v -w5 127.0.0.1 1122
Sometimes it happens that the external connection dies, so my netstat
output will be
`tcp6 0 0 203.0.113.10:22 10.34.23.12:62734 ESTABLISHED`
Is there a way to check which tunnel does not have an external port listening?
I mean, is there a way to check when my 1122 port dies?
My solution would be kill the sshd process binded to the tunnel without any external port (10.34.23.12:62734). The problem is that I've an other SSH tunnel on this machine I would not like to kill, so killall sshd
would not be an option.
Thank you!
Edit 1:
Possible solution: The netstat -lptun command (and the netstat -pant suggested by Paul) does the binding I need to try to solve this. Now I'm testing this solution in production.
#!/bin/sh
for pid in `lsof -i -n | egrep '\<ssh\>' | awk '{print $2}'`; do
foundpid="$(netstat -lptun | grep :::11 | grep $pid)"
if [ -z "$foundpid" ]
then
echo PID does not have any external port, killing the pid $pid
kill $pid
fi
done
netstat -pant
, are both netstat lines owned by the same process, and different to the other ssh process you want to keep?