List outbound ssh sessions
tl;dr
sudo netstat -Watp | grep 'ESTABLISHED.*ssh' | awk '{print $5}' | sed 's/:ssh//;' | sort | uniq | while read line; do ps -ef | grep -o "ssh\s.*${line}"; done | sort | uniq | sed -r -e 's/ssh //g;' -e 's/-l (\w*) /\1@/;'
Backstory
During other work, it came up that I was interested in seeing what outbound ssh sessions I was using. Now I don't even know why it came up, because I was just writing a shell script to programmatically adjust my xfce settings using its xfconf-query API.
Walking through the command
sudo netstat -Watp | grep 'ESTABLISHED.*ssh' | awk '{print $5}' | sed 's/:ssh//;' | sort | uniq | while read line; do ps -ef | grep -o "ssh\s.*${line}"; done | sort | uniq | sed -r -e 's/ssh //g;' -e 's/-l (\w*) /\1@/;'
This whole statement lists the established ssh connections and then finds the running processes for those and tries to identify the usernames for them. Step by step: Everything before the while collects the list of established ssh connections. sudo netstat -Watp | grep 'ESTABLISHED.*ssh' gets the list of ssh connections, and awk | sed | sort | uniq just gets the information we want from each row and removes duplicates. The while read line; do :; done loop iterates over the list. So for each line in the list, search all running processes for that name on the same line as the expression 'ssh.' sort | uniq removes duplicates (apparently qemu+kvm in virt-manager uses a lot of separate ssh processes). sed -r -e 's/ssh //g;' -e 's/-l (\w*) /\1@/;' trims extra characters and also converts compatible outputs into "username@hostname."
Improvements to be made
This snippet as is only works if the ssh command issued matches exactly the description of the output of netstat. If dns reverse zones are not configured correctly, so that the netstat shows an IP address but the ssh command was a hostname, this snippet will not find it. I need to improve that, which will probably require a fancier script and not just a oneliner.
Comments