14

How can I get list of open SSH tunnels?


I'm using Mac OS X client connected to FreeBSD server. I'm trying to query open tunnels on the client.

Eonil
  • 9,689
  • 15
  • 34
  • 53
  • What OS would this be on? Is this your server? Do you have root access to it? Please edit your question and include more information. – EEAA Mar 11 '11 at 02:53
  • Check your [other question](http://serverfault.com/questions/246030/how-can-i-close-ssh-tunnel-gracefully/246035#246035), the answer I gave there will solve that too. – coredump Mar 11 '11 at 03:14
  • Are you looking at one session with multiple tunnels or multiple sessions? Pretty different topic :) – Blitz Mar 11 '11 at 13:29

5 Answers5

12

You can use lsof:

$ lsof -i tcp | grep ^ssh
ssh       2211 lcipriani    3r  IPv4  20825      0t0  TCP lcipriani-laptop.local:49164->docsuite.cefla.com:22 (ESTABLISHED)
ssh       2223 lcipriani    3r  IPv4  21945      0t0  TCP lcipriani-laptop.local:34471->gd-b-21.vps.redomino.com:22 (ESTABLISHED)
ssh       2640 lcipriani    3r  IPv4  37488      0t0  TCP lcipriani-laptop.local:45693->makeda-xen1.redomino.com:22 (ESTABLISHED)
ssh       5279 lcipriani    3r  IPv4 212324      0t0  TCP lcipriani-laptop.local:56491->67.227.82.162:22 (ESTABLISHED)
ssh       5279 lcipriani    4u  IPv6 210281      0t0  TCP lcipriani-laptop:10000 (LISTEN)
ssh       5279 lcipriani    5u  IPv4 210282      0t0  TCP localhost.localdomain:10000 (LISTEN)

The last line represent a tunnel (look at the state LISTEN).

lcipriani
  • 231
  • 1
  • 3
  • You can also use `lsof`'s built-in filter using `-c` flag. So, `lsof -i tcp -c '/^ssh/'`. – Volte Feb 24 '20 at 19:05
4

In Ubuntu, with iptables and iptstate installed and standard ssh port:

iptstate -D 22

each line will represent open tunnel.

alexm
  • 458
  • 3
  • 11
3

If you're trying to find out what's using the tunnel(s) in a single ssh session, type ~# at the beginning of a line.

geekosaur
  • 7,025
  • 1
  • 19
  • 19
2
/sbin/ip tunnel list # replacement for the deprecated iptunnel command
Lucas Cimon
  • 253
  • 2
  • 6
0

Using lcipriani's answer in a script:

sessions=$(lsof -i tcp | grep "^ssh" | grep ESTABLISHED)
if [ -z "sessions" ]; then
    echo "no open ssh sessions"
else
    echo "ssh sessions are open"
fi
user206746
  • 186
  • 1
  • 3