Bash script To change password of a mail account in cPanel via command line
The bash script given below will help you to change the password of a single mail account in a cpanel server via command line.Let the script name is 'changemailpass.sh'. You can change the password of a mail account by using the following format.
# ./changemailpass.sh <mail_account> <newpassword>
#!/bin/bash -
#title :changemailpass.sh
#description :To change password of a single mail account in cPanel via terminal
#author :Arun Ghosh
#date :20130811
#version :1.0
#usage :./changemailpass.sh
#notes :
#bash_version :4.2.25(1)-release
#============================================================================
MAIL_USER=$1
NEW_PASS=$2
MAIL_FLAG=false
DOMAIN=$(echo $MAIL_USER | cut -d"@" -f2)
MAIL=$(echo $MAIL_USER | cut -d"@" -f1)
EXIST=`grep ^$DOMAIN /etc/userdomains`
if [ "$EXIST" ]
then
CP_USER=`grep ^$DOMAIN /etc/userdomains | cut -d":" -f2 | tr -d ' '`
SHADOW_FILE="/home/$CP_USER/etc/$DOMAIN/shadow"
cat /dev/null > "/home/$CP_USER/etc/$DOMAIN/shadow.tmp"
for shadow in `cat /home/$CP_USER/etc/$DOMAIN/shadow`
do
pass=$(openssl passwd -1 $NEW_PASS)
user=$(echo $shadow | cut -d":" -f1)
rest=$(echo $shadow | cut -d":" -f3-)
if [ "$user" == "$MAIL" ]
then
MAIL_FLAG=true
echo "$user":$pass:$rest >> /home/$CP_USER/etc/$DOMAIN/shadow.tmp
else
echo $shadow >>/home/$CP_USER/etc/$DOMAIN/shadow.tmp
fi
done
if [ $MAIL_FLAG = false ]
then
echo "$1 not exists..!!";
elif [ $MAIL_FLAG = true ]
then
echo "$1 password changed to: $2"
fi
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"
else
echo "Domain not in the server"
fi