Getting list of opened ssh connections by name
I have a config file in my .ssh dir that looks like this
Host somehostA
HostName 123.45.67.89
User katsh
So from my local machine, i can ssh into multiple machines by their name in the config file, like so
ssh somehostA
ssh somehostB
ssh somehostC
...
etc
Is it possible to get a list of all machines i am connected to, by their name?
I know I can do:
lsof -i tcp -n | grep '\<ssh\>'
and i'll get something like
ssh 9871 katsh 3u IPv4 400199 0t0 TCP 987.654.2.2:47329->987.654.2.2:47329:ssh (ESTABLISHED)
ssh 20554 katsh 3u IPv4 443965 0t0 TCP 123.456.7.8:41923->123.456.7.8:ssh (ESTABLISHED)
But it does not list their names, just IP
Solution 1:
If you just want a list of names you can do something like this
sudo netstat -atp | grep 'ESTABLISHED.*ssh ' | awk '{print $5}'| sed 's/:ssh//'
- get the list of used ports
- filter out those that are ssh related. You need a space after ssh to remove the inbound connections to the local sshd.
- get the name from the list
- remove the :ssh
Some example output, without the filter for sshd
host1.lan
192.168.1.71:51053
192.168.1.71:50323
host2.lan
192.168.1.71:50929
which shows the outgoing connections to host1 and host2 but also shows the inbound connections for the putty sessions I have to the demonstration host.
Some example output with the local sshd connections filtered out
host1.lan
host2.lan
Solution 2:
The w
command seems to do it - I've connected from my test VM, from my desktop (BLACKBEAUTY) then sshed from the VM into my VPS (example.com - not my real domain) and the output is as follows
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
geek pts/2 blackbeauty 21:31 1:46 0.63s 0.02s ssh example.com
geek pts/3 blackbeauty 21:32 0.00s 0.57s 0.00s w
Tie that in with grep ssh
and you should be able to extract lines where WHAT is ssh for more clarity.
Solution 3:
$ sudo netstat -atp | grep 'ESTABLISHED.*ssh'