Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 4 down vote accepted

Active ssh connection:

# netstat -an | grep -E "\:22[ \t]+" | grep ESTABLISHED | wc -l

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}"
share|improve this answer
Thanks for answering. – Jamie Jan 31 '11 at 1:01
Consider grep -c ESTABLISHED instead of filtering all those through wc -l – James Feb 9 '11 at 11:13

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) "

share|improve this answer

Your Answer


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.