Automating WordPress Setup with MySQL and Command-Line Operations Using Python

Introduction
Setting up a WordPress site involves multiple steps, from creating a MySQL database and user to configuring the necessary file system permissions. You can automate these tasks using Python by combining MySQL operations and executing system commands through the command-line interface.

In this article, we’ll walk through how to:

  1. Create a MySQL database and user using Python.
  2. Set up WordPress, configure file permissions, and deploy WordPress files.
  3. Use Python’s command-line argument handling to pass variables for database and site configuration.

We will use the mysql-connector-python package to interact with the MySQL database and Python’s subprocess module to execute the necessary shell commands.

Prerequisites

Before running the script, ensure that:

  • MySQL is installed and running.
  • Python is installed with mysql-connector-python installed.
  • You have root access to perform the required file operations and permissions changes.

Step 1: Install Required Libraries

To install the mysql-connector-python library, run:

pip install mysql-connector-python

Step 2: Python Script with Command-Line Arguments

In this script, we will:

  • Create a MySQL database and user.
  • Set the correct permissions on the WordPress folder.
  • Download and extract WordPress.
  • Configure WordPress for the new site.

The script accepts arguments for the site domain, database name, user, and password, allowing for flexible use across multiple site setups.

Here’s the Python script that automates this process:

import mysql.connector
from mysql.connector import Error
import subprocess
import sys
import os

def create_mysql_db_user(db_name, user_name, user_password):
    """ Create a MySQL database and user """
    try:
        connection = mysql.connector.connect(
            host="localhost",
            user="root",  # Root user
            password="root_password"  # Replace with actual root password
        )

        if connection.is_connected():
            cursor = connection.cursor()

            # Step 1: Create the database
            cursor.execute(f"CREATE DATABASE {db_name}")
            print(f"Database '{db_name}' created successfully.")

            # Step 2: Create the user
            cursor.execute(f"CREATE USER '{user_name}'@'localhost' IDENTIFIED BY '{user_password}'")
            print(f"User '{user_name}' created successfully.")

            # Step 3: Grant privileges
            cursor.execute(f"GRANT ALL PRIVILEGES ON {db_name}.* TO '{user_name}'@'localhost'")
            print(f"Granted privileges on '{db_name}' to '{user_name}'.")

            # Step 4: Apply the changes with FLUSH PRIVILEGES
            cursor.execute("FLUSH PRIVILEGES")
            print("Privileges applied successfully.")

    except Error as e:
        print(f"Error: {e}")

    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()

def run_command(cmd):
    """ Run a shell command """
    try:
        subprocess.run(cmd, shell=True, check=True)
    except subprocess.CalledProcessError as e:
        print(f"Command '{cmd}' failed: {e}")

def setup_wordpress(site_domain):
    """ Set up WordPress for the specified site domain """
    site_path = f"/var/www/{site_domain}"

    # Step 1: Create the website directory and set permissions
    run_command(f"sudo mkdir -p {site_path}")
    run_command(f"sudo chown -R www-data:www-data {site_path}")
    run_command(f"sudo chmod -R 755 {site_path}")

    # Step 2: Download and extract WordPress
    run_command("cd /tmp && wget https://wordpress.org/latest.tar.gz")
    run_command("tar -xvzf /tmp/latest.tar.gz -C /tmp")

    # Step 3: Copy WordPress files to the site directory
    run_command(f"sudo cp -r /tmp/wordpress/* {site_path}")
    run_command(f"sudo chown -R www-data:www-data {site_path}")
    run_command(f"sudo chmod -R 755 {site_path}")

    # Step 4: Copy the wp-config sample
    run_command(f"cd {site_path} && sudo cp wp-config-sample.php wp-config.php")
    print(f"WordPress set up for {site_domain}.")

def main():
    if len(sys.argv) != 5:
        print("Usage: python script.py <site_domain> <db_name> <db_user> <db_password>")
        sys.exit(1)

    site_domain = sys.argv[1]
    db_name = sys.argv[2]
    db_user = sys.argv[3]
    db_password = sys.argv[4]

    # Step 1: Create the MySQL database and user
    create_mysql_db_user(db_name, db_user, db_password)

    # Step 2: Set up WordPress
    setup_wordpress(site_domain)

if __name__ == "__main__":
    main()

Step 3: Explanation of the Script

Command-Line Arguments

The script takes four command-line arguments:

  1. site_domain – The domain name of the WordPress site (e.g., site1.com).
  2. db_name – The MySQL database name to create.
  3. db_user – The MySQL user to create.
  4. db_password – The password for the MySQL user.

You can run the script as follows:

python script.py site1.com wp_site1 wp_user1 password1

MySQL Operations

We use the mysql-connector-python library to interact with MySQL. The create_mysql_db_user() function handles:

  1. Creating the database.
  2. Creating the user.
  3. Granting the user all privileges on the newly created database.
  4. Applying the privileges with FLUSH PRIVILEGES.
def create_mysql_db_user(db_name, user_name, user_password):
    try:
        connection = mysql.connector.connect(
            host="localhost",
            user="root",  # Root user
            password="root_password"
        )
        # Database creation, user creation, and privileges
        # ...

WordPress Setup

The setup_wordpress() function executes the necessary shell commands to:

  1. Create the site directory.
  2. Set the ownership and permissions.
  3. Download and extract WordPress.
  4. Copy the wp-config-sample.php to wp-config.php.
def setup_wordpress(site_domain):
    site_path = f"/var/www/{site_domain}"
    run_command(f"sudo mkdir -p {site_path}")
    run_command(f"sudo chown -R www-data:www-data {site_path}")
    run_command(f"sudo chmod -R 755 {site_path}")
    run_command("cd /tmp && wget https://wordpress.org/latest.tar.gz")
    run_command(f"sudo cp -r /tmp/wordpress/* {site_path}")
    # ...

Subprocess Execution

We use Python’s subprocess.run() to execute shell commands:

def run_command(cmd):
    try:
        subprocess.run(cmd, shell=True, check=True)
    except subprocess.CalledProcessError as e:
        print(f"Command '{cmd}' failed: {e}")

Step 4: Running the Script

  1. Open your terminal and navigate to the directory where the Python script is saved.
  2. Run the script with the appropriate arguments:
python script.py site1.com wp_site1 wp_user1 password1

The script will create the MySQL database, set up the WordPress site, and configure everything necessary for the domain you specified.


Conclusion
Automating the setup of a WordPress site using Python not only saves time but ensures consistency when setting up multiple environments. With this script, you can efficiently create a MySQL database, configure file permissions, and deploy WordPress for a given site domain.

Edvaldo Guimrães Filho Avatar

Published by

Leave a comment