cPanel - Bash script To Change/reset all email account password using command line

 Bash script To Change/reset password of all mail accounts via terminal

Once I got a project to reset the passwords of all mail accounts in a cpanel server. At that time I was not at all good in bash scripts, later when I got free time I decided to develop a bash script for the purpose. It may be easily done by perl scripts, I think there are modules to do it easily. But I dont know perl scripting, this is the one I am comfortable with.

The bash script given below will change/reset the password of all the mail accounts in a cpanel server. The new password with mail account user name will be saved in to '/root/mailaccounts.txt'.




#!/bin/bash -  
#title            :changeallmailpass.sh
#description      :To Change password of all mail accounts in a cPanel Server
#author           :Arun Ghosh
#date             :20130812
#version          :1.0   
#usage            :./changeallmailpass.sh
#notes            :      
#bash_version :4.2.25(1)-release
#============================================================================

genpasswd() {

        tr -dc A-Za-z0-9_ < /dev/urandom | head -c 12 | xargs
}

cat /dev/null > /root/mailaccounts.txt

CP_ACCOUNTS=`ls -1A /var/cpanel/users/`

for CP_USER in `echo -n $CP_ACCOUNTS`
do
    USER_DOMAIN=`grep -i ^dns /var/cpanel/users/$CP_USER |cut -d= -f2`
    for DOMAIN in `echo -n "$USER_DOMAIN"`
    do
        SHADOW_FILE="/home/$CP_USER/etc/$DOMAIN/shadow"
        if [ -f $SHADOW_FILE ] && [ -s $SHADOW_FILE ]
        then 
            cat /dev/null > "/home/$CP_USER/etc/$DOMAIN/shadow.tmp"
            for shadow in `cat $SHADOW_FILE`
            do

                NEW_PASS=$(genpasswd)
                MD5_PASS=$(openssl passwd -1 $NEW_PASS)
                user=$(echo $shadow | cut -d":" -f1)
                rest=$(echo $shadow | cut -d":" -f3-)

                echo -e "$NEW_PASS\t$user@$DOMAIN" >> "/root/mailaccounts.txt"
                echo "$user:$MD5_PASS:$rest" >> "/home/$CP_USER/etc/$DOMAIN/shadow.tmp"
               
            done
            mv "/home/$CP_USER/etc/$DOMAIN/shadow" "/home/$CP_USER/etc/$DOMAIN/shadow.$(date +%s)"
            mv "/home/$CP_USER/etc/$DOMAIN/shadow.tmp" "/home/$CP_USER/etc/$DOMAIN/shadow"
            chmod 640 "/home/$CP_USER/etc/$DOMAIN/shadow"
            chown $CP_USER:$CP_USER "/home/$CP_USER/etc/$DOMAIN/shadow"         
       fi
    done
done

========================================================================

I have tested this script already. If there is any bugs you found in this scripts, hope you will report it....

One thought on “cPanel - Bash script To Change/reset all email account password using command line”