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 script that programmatically creates users, but we'd like to delete the users after 48 hours, as well as any files they own.

I know you can set an expiration with the useradd command, but I don't know how to take the next step of deleting the user and its associated files on expiration.

Is there an easy way to do this?

Thank you!

share|improve this question

4 Answers 4

up vote 2 down vote accepted

Assuming you have a user creation script that sets $username, add this:

cat <<EOF | at now + 2 days
userdel -f -r $username
EOF

It also pays to set an expiration on the account when it is added, as extra insurance.

share|improve this answer
    
Perfect, that's what I did. Thanks Jeff! –  Noah_R-C Mar 3 '11 at 4:07

If you are setting up accounts to expire 2 days after you set them up then the script below should help.

#!/bin/bash
#
nowsecs=$( date +%s )

while read account
do
    username=$( echo $account | cut -d: -f1  )
    expiredays=$( echo $account | cut -d: -f2 )
    expiresecs=$(( $expiredays * 86400 ))
    if [ $expiresecs -le $nowsecs ]
    then
        echo "$username has expired deleting"
        userdel -r "$username"
    fi
done < <( cut -d: -f1,8 /etc/shadow | sed /:$/d )

When it's run it reads the shadow file and selects accounts with expiry dates set. For each selected account it works out if now is later than the expiry time. If it is it deletes the account.

Making sure you have backups before testing this.

share|improve this answer

If you are already marking them as "expired" you could try a cron task to schedule daily, hourly or weekly account cleanups. You just create a script just like the one you wrote to create the user, but to detect expiration and delete whatever you need to. Make sure it runs as root.

share|improve this answer

Probably a good idea would be to use a mixture of crontab + file containing usernames to delete? Delimit that file with necessary dates maybe, or run a cron job that looks for expired users and deletes them. A simple shell script can do this.

share|improve this answer

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.