Fixing File and Directory Permissions for cPanel Users with a Bash Script
Managing file and directory permissions on a cPanel server is crucial for both security and functionality. Incorrect permissions can expose sensitive data or cause website errors. This guide shows you how to use a Bash script to quickly fix permissions for cPanel users.
Why Are Permissions Important?
In Linux systems, permissions determine who can read, write, or execute files and directories. The most common permission settings are:
- Directories:
755
– Owner has full control; others can read and execute. - Files:
644
– Owner can read and write; others can only read.
These settings protect your files while allowing websites to function correctly.
Bash Script to Fix Permissions
Here’s a simple Bash script to adjust permissions for a specific cPanel user:
#!/bin/bash
# Script to fix permissions for a cPanel user
if [ "$#" -lt "1" ]; then
echo "Must specify user"
exit
fi
USER=$@
for user in $USER; do
HOMEDIR=$(egrep "^${user}:" /etc/passwd | cut -d: -f6)
if [ ! -f /var/cpanel/users/$user ]; then
echo "$user user file missing, likely an invalid user"
elif [ "$HOMEDIR" == "" ]; then
echo "Couldn't determine home directory for $user"
else
echo "Setting ownership and permissions for user $user"
chown -R $user:$user $HOMEDIR
chmod 711 $HOMEDIR
chown $user:nobody $HOMEDIR/public_html $HOMEDIR/.htpasswds
chown $user:mail $HOMEDIR/etc $HOMEDIR/etc/*/shadow $HOMEDIR/etc/*/passwd
find $HOMEDIR -type f -exec chmod 644 {} \; -print
find $HOMEDIR -type d -exec chmod 755 {} \; -print
find $HOMEDIR -type d -name cgi-bin -exec chmod 755 {} \; -print
find $HOMEDIR -type f \( -name "*.pl" -o -name "*.perl" \) -exec chmod 755 {} \; -print
fi
done
chmod 750 $HOMEDIR/public_html
if [ -d "$HOMEDIR/.cagefs" ]; then
chmod 775 $HOMEDIR/.cagefs
chmod 700 $HOMEDIR/.cagefs/tmp
chmod 700 $HOMEDIR/.cagefs/var
chmod 777 $HOMEDIR/.cagefs/cache
chmod 777 $HOMEDIR/.cagefs/run
fi
How to Use the Script
- Save the Script: Save the code to a file named
fixperms.sh
. - Make It Executable: Run
chmod +x fixperms.sh
to make the script executable. - Run the Script: Execute the script by running
bash fixperms.sh <username>
, replacing<username>
with the cPanel username.
Conclusion
This script provides a quick way to standardize file and directory permissions for cPanel users, enhancing security and functionality. Always test scripts in a safe environment before applying them to production servers.
By following these steps, you can ensure that your cPanel environment is secure and operating smoothly.