• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

    Don’t let server issues slow you down. Let us manage them for you.

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

Copyright © 2008 – 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy
Email account password reset script – cPanel

Email account password reset script – cPanel

Siju Jacob

  • 4 min read
Email account password reset script – cPanel

Generating audio, please wait...

We all know the cPanel reset email password option in cPanel. Yeah, navigate to cPanel >> Email Accounts and reset the password against the email account.

It is a bit time consuming, right? And what if you have only WHM Access?

Then you will have to select the account and drop into its cPanel account which adds an additional step and delay our time even more. What if we had a simple utility to reset email passwords through Command line. It would just get things done in a few seconds saving us a few minutes of our time *and the clients time ;)*.

The python script I have written here is to do exactly that.  The script can be executed as a cPanel user also to reset passwords of email accounts under his account. It is achieved through eliminating the use of cPanel API Calls, hence only a few modifications are required for the user level execution.

The script I have written below requires root privileges for the script to be executed and can only be run on a cPanel server.

cPanel reset email password Script :-


# -*- coding: utf-8 -*-
#!/usr/bin/env python
####################################################
import os
import subprocess
import logging
#####################################################
#logging at /var/log/emailpassreset.log
#####################################################
logger = logging.getLogger('myapp')
hdlr = logging.FileHandler('/var/log/emailpassreset.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.DEBUG)
#########change as True to disable logging##########
logger.disabled = False
####################################################
#Check if there is root privilage
####################################################
if os.geteuid() != 0:
    exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")
####################################################
#Check if host is running a cPanelserver
####################################################
FNULL = open(os.devnull, 'w')
try:
	subprocess.check_call(["/usr/local/cpanel/cpanel", "-V"], stdout=FNULL, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
	exit("Server is not running cPanel.\n Exiting.")
####################################################
#Split Account Details
####################################################
def print_account():
    account, domain = EmailAccount.split("@")
    print ("Account: %s " % account)
    print ("Domain: %s " % domain)
####################################################
#Check if Email Account entered is of valid format
####################################################
def check_email_validity():
    split_build_descriptor = EmailAccount.split("@")
    if len(split_build_descriptor) == 2:
        print_account() #calling function
    else:
        print ("Email Address invalid. Try entering the complete email account. Eg: [email protected]")
        logger.error("Email Address invalid")
        exit()    
######################################################
#Check if domain, mail directory and shadow file exists
#and update the password
######################################################    
def check_domain_exists():
    import os
    import os.path
    import crypt
    import random
    import string
    account, domain = EmailAccount.split("@")
    check_userdomain = False
    userdom = os.path.join(os.sep, 'etc', 'userdomains')
    domain1 = open(userdom, "r")
    for line in domain1:
	  if line.startswith(domain):
	       check_userdomain =  line
	  else:
	       pass
    if check_userdomain:
        logger.info("Account exists in userdomains")
        username1 = check_userdomain.split (":")[1].strip()
	homedir = os.path.join(os.sep, 'etc','passwd')
	for line in open(homedir):
 		if username1 in line:
	 		homedir1 = line.split (":")[5].strip()
        maildir = os.path.join(os.sep, homedir1, 'mail', domain, account)
        if os.path.exists(maildir):
            logger.info("Mail directory exists =%s" % maildir)
            shadowpath = os.path.join(os.sep, homedir1, 'etc', domain, 'shadow')
	    showentry = False
	    for line in open(shadowpath):
 		if account in line:
	 		old_hash = line.split (":")[1].strip()
			showentry = True
		else:
			pass
            if showentry:
                passwd = raw_input("Enter new Email Password:")
                saltvalue = '$1$' + ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(8)])
                new_hash = crypt.crypt(passwd, saltvalue)
                s=open(shadowpath).read()
                if old_hash in s:
                    print"-------------------------------------------------------------------"
                    s=s.replace(old_hash, new_hash)
                    f=open(shadowpath, 'w')
                    f.write(s)
                    print "Password changed successfully to %s" % passwd
                    logger.info("Password changed successfully")
                    f.flush()
                    f.close()
                else:
                    print 'No occurances of "{old_string}" found.'.format(**locals())
                    logger.error("No occurances of shadow entry found.Try again")
                    exit()
            else:
                print "Error: Shadow entry not found"
                logger.error("Error: Shadow entry not found")
                exit()
        else:
            print "Error: Mail Directory not found"
            logger.error("Error: Mail Directory not found")
            exit()
    else:
        print 'The entered domain does not exist in this server'
        logger.error("The entered domain does not exist in this server")
        exit()
###################################################
#Script
###################################################
EmailAccount = raw_input("Enter Email Account:")
print ("EmailAccount: %s " % EmailAccount)
logger.info("Email Account to reset password: %s " %EmailAccount)
check_email_validity()
check_domain_exists()

Get Dedicated Webhosting Support Team

  • cPanel
  • Howtos
  • Linux

BitCoin – Introduction

BitCoin – Introduction
  • General
logo

Bitcoin Mining

Bitcoin Mining
  • General
logo

How to enable RAID Monitoring in Nagios

How to enable RAID Monitoring in Nagios
  • Linux
logo

Posts by Siju Jacob

Web enthusiast and tech savvy, curious to solve and find solutions to seemingly difficult tasks. Currently working as System Engineer at SupportSages and although his skill set is vast, his greatest expertise revolve in the worlds of system administration.