How to Clear Your /tmp Folder Automatically?

Is your /tmp directory simply getting overrun with SESS files? If so, try this:

make a file in scripts called cleantmp, put the following in it:

************
# This script cleans out /tmp of empty, root, cpanel
# and nobody session files in /tmp
# rev 2.0b by Darren - 8.19.07

# if --test is passed, we just show the results
if [ "$1" == "--test" ]
then
CMD="-exec ls -la"
echo "$0: test mode"
else
CMD="-exec rm -rf"
fi

if [ "$1" == "--help" ]
then
echo ""
echo "cleantmp will clean out your tmp directory for you"
echo ""
echo "Parameters:"
echo "--test to run in test mode"
echo "--help display this file"
echo "-a accountname to remove all files owned by account name"
echo "-e cleans out all empty (zero length) files"
echo ""
exit 0
fi

if [ "$1" == "-a" ]
then
echo ""
echo "Removing session file for account $2"
find /tmp -name "sess*" -user $2 -maxdepth 1 $CMD {} \;
echo "completed"
echo ""
exit 0
fi

if [ "$1" == "-e" ]
then
echo ""
echo "Cleaning out empty files from /tmp"
find /tmp -name "sess*" -empty -maxdepth 1 $CMD {} \;
echo "completed"
echo ""
exit 0
fi


# remove empty session files that are over 2 hours old
find /tmp -name "sess*" -empty -mmin +120 -maxdepth 1 $CMD {} \;

# remove root owned session files
find /tmp -name "sess*" -user root -maxdepth 1 $CMD {} \;

# remove nobody session files
find /tmp -name "*sess*" -user nobody -maxdepth 1 $CMD {} \;

# remove cpanel owned session files
find /tmp -name "sess*" -user cpanel -maxdepth 1 $CMD {} \;

# remove any session file over 5 hours old
find /tmp -name "sess*" -mmin +300 -maxdepth 1 $CMD {} \;

# remove any spamassassin file over 4 hours old
find /tmp -name ".spamassassin*" -mmin +240 -maxdepth 1 $CMD {} \;
************

Now save, and chmod it so it can be run (use your discretion for perm level):
chmod 755 /scripts/cleantmp

Run it as /scripts/cleantmp --test to view which files will be removed or /scripts/cleantmp -a accountname to remove all files owned by account name. And running it with "-e" will remove all empty session files.

What we do on most boxes is have it run in cron.hourly so that it purges session files. It cleans empties that are over 2 hours old, and normal ones that are over 5 hours old. Keep in mind, this may break software that uses "Keep Me Logged In Indefinitely" option for users. But the script could be easily modified to skip some session files if needed.

So, go to /etc/cron.hourly and create a file called cleantmp. Put this into it:

****************
#!/bin/bash

/scripts/cleantmp -e >/dev/null 2>&1
/scripts/cleantmp >/dev/null 2>&1
****************

and save it, then do the same permissions procedure as above. Now every hour, the script wil clean out empty and older SESS files and keep your sites up. Modify this and the other script as needed.

Hope this helps! Suggestions, questions are welcome.

    0 comments: