Automatically shut down server on inactivity (SSH)?
As of January 2013 Amazon CloudWatch provides an option to Use Amazon CloudWatch to Detect and Shut Down Unused Amazon EC2 Instances, see the introductory blog post Amazon CloudWatch - Alarm Actions for details on this functionality:
Today we are giving you the ability to stop or terminate your EC2 instances when a CloudWatch alarm is triggered. You can use this as a failsafe (detect an abnormal condition and then act) or as part of your application's processing logic (await an expected condition and then act). [emphasis mine]
Your use case is listed in section Failsafe Ideas specifically:
If you (or your developers) are forgetful, you can detect unused EC2 instances and shut them down. You could do this by detecting a very low load average for an extended period of time. This type of failsafe could be used to reduce your AWS bill by making sure that you are not paying for resources you're not actually using.
As outlined, this depends on being able to heuristically detect the appropriate condition triggering the alarm and stopping the instance - you might take it to the next level by means of Publishing Custom Metrics to CloudWatch based on the logged in SSH user count, idle time or else and gain more control/precision for the desired detection and shutdown process in turn.
You could create a cron job script right on the instance itself that uses a command like
netstat | grep ssh | grep ESTABLISHED
and if no result is returned write that to file, then the cron tries again and if it returns no results again the script runs this.
/sbin/shutdown -h now
If all you're looking for is to keep the server running while you're logged-in, and your session idle for less than
n units of time, you can do so via a cron script which you mentioned, by monitoring the output of
w(1) which reports
IDLE time for logged-in user, which you can use.