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 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
add comment

2 Answers

up vote 4 down vote accepted

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}"
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
add comment

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
add comment

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.