How does one determine active SSH and SAMBA connection counts?
I have a server that I use infrequently, so I'd like to cron
a job to shutdown daily if no users are logged in via SSH and SAMBA shares.
How can I determine how many active SSH connections there are, and how many active SAMBA connections there are?
If both of these values are zero, the cron script will shutdown the server.
Solution 1:
Active ssh connection:
# netstat -an | grep -E "\:22[ \t]+" | grep ESTABLISHED | wc -l
1
Active Samba connection:
# netstat -an | grep -E "\:445[ \t]+" | grep ESTABLISHED | wc -l
or use lsof:
SSHCONNECTION=`lsof -i :22 | grep ESTABLISHED | wc -l`
SAMBACONNECTION=`lsof -i :445 | grep ESTABLISHED | wc -l`
echo "SSH connection: ${SSHCONNECTION} Samba connection ${SAMBACONNECTION}"
Solution 2:
You can check any active connections to any service by using the following command
netstat -an | grep ESTABLISHED | grep ":[portname] " | wc -l
By portname you need to select the port of the service you're looking into, for SSH that'll be port 22 (so it should be grep ":22 "
) (the space behind just makes sure that it's not another port.
If you want to select more than one port (as it would be in samba) change grep for egrep ":(port|port|port) "