Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question

3 Answers 3

up vote 4 down vote accepted

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
share|improve this answer
    
awk can do a grep: sudo netstat -atp | awk '/ESTABLISHED.*ssh/ { print $5 }'.... –  quanta Sep 24 '12 at 2:36
    
@quanta: ooh yes, I keep forgetting about that - thanks. –  Iain Sep 24 '12 at 19:44

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.

share|improve this answer
$ sudo netstat -atp | grep 'ESTABLISHED.*ssh'
share|improve this answer
    
@Downvoter: Could you please leave a comment? –  quanta Sep 23 '12 at 8:13
    
Yeah that was unfair. i upvoted. every answer appreciated. –  lyrae Sep 24 '12 at 0:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.