I created an automated script that makes deleting someone from my email server a little easier. The script is very basic and just helps me do the following:
1 - back up their home directory.
2 - check to see if they're subscribed to any Mailman lists and removes them to avoid delivery failures.
3 - checks '/etc/aliases' for any entries.
4 - Removes the user and their home directory using the userdel -r "command"
It's very basic and I have never written a script before so please excuse me if I am doing anything wrong. Two things I would like to understand how to do in this script before I use it.
First is to somehow find a way to copy / backup their '/etc/passwd & '/etc/shadow' entry in case I ever need to restore their account for an unknown reason. Is this possible?
Second is I find out the hard way if I run the script on my mail server with no username following it:
Rather than how it's intended:
Code:
sh remove_user.sh carlos
The script will run and just start backing up the entire /home/* directory. If you did not happen to catch this process, you risk the script backing up the entire home directory and eventually deleting all accounts. Is there a way I can change the script that must require a username after the script name?
Below is the script I wrote:
Code:
#!/bin/bash
USERNAME=$1
HOMEDIR=/home/$USERNAME
BACKUPDIR=/var/backup
MAILMANDIR=/usr/lib/mailman
DATESTAMP=$(date +%m-%d-%Y_%H-%M)
if [ -d /home/$USERNAME ]; then
echo "* Backing up home directory to $BACKUPDIR:"
tar jcvf $BACKUPDIR/$USERNAME-$DATESTAMP.tar.bz2 /home/$USERNAME
echo "--------------------------------------------------"
fi
echo "--------------------------------------------------"
echo "* Removing user from mailing lists:"
$MAILMANDIR/bin/remove_members --fromall $USERNAME@mydomain
echo "--------------------------------------------------"
echo "--------------------------------------------------"
echo "* Checking alias files for entries:"
ALIASFILES=$(ls /etc/*alias* | grep -v '\.db' | grep -v '\.orig')
for f in $ALIASFILES; do
grep -H $USERNAME $f
done
echo "--------------------------------------------------"
echo "--------------------------------------------------"
echo "* Removing users home directory - /home/$USERNAME:"
userdel -r $USERNAME
echo "--------------------------------------------------"