Shell – List open SSH tunnels

shellsshssh-tunnel

I use a lot of SSH tunnels to various servers on my linux machine (for tunnelling to databases, web servers etc) and it would be really handy to view a list of current open tunnels via a shell script.

I can identify local connections via a grep on netstat along the lines of:

netstat -n --protocol inet | grep ':22'

but this won't show me the remote port its connected to (and obviously includes standard SSH connections that aren't tunnelled)

UPDATE: The answers are fine but are not showing me the remote port I'm connected to. E.g I often have a tunnel through to mysql, say localhost:3308 mapping to :3306 on the server. Normally I can guess by the local ports I've chosen but would be nice to have access to both.

Any ideas?

Best Answer

if you only want to list tunnels created by ssh:

% sudo lsof -i -n | egrep '\<ssh\>'
ssh  19749  user  3u  IPv4 148088244   TCP x.x.x.x:39689->y.y.y.y:22 (ESTABLISHED)
ssh  19749  user  4u  IPv6 148088282   TCP [::1]:9090 (LISTEN)
ssh  19749  user  5u  IPv4 148088283   TCP 127.0.0.1:9090 (LISTEN)

(that would be a -L 9090:localhost:80 tunnel)

if you want to see the tunnels / connections made to a sshd:

 % sudo lsof -i -n | egrep '\<sshd\>'
sshd  15767  root  3u  IPv4 147401205   TCP x.x.x.x:22->y.y.y.y:27479 (ESTABLISHED)
sshd  15842  user  3u  IPv4 147401205   TCP x.x.x.x:22->y.y.y.y:27479 (ESTABLISHED)
sshd  15842  user  9u  IPv4 148002889   TCP 127.0.0.1:33999->127.0.0.1:www (ESTABLISHED)
sshd  1396   user  9u  IPv4 148056581   TCP 127.0.0.1:5000 (LISTEN)
sshd  25936  root  3u  IPv4 143971728   TCP *:22 (LISTEN)

the ssh-daemon listens on port 22 (last line), 2 subprocesses are spawned (first 2 lines, login of 'user'), a -R tunnel created on port 5000, and a -L tunnel which forwards a port from my (local) machine to localhost:80 (www).

Related Question