Quickly create Apache virtual hosts using a bash script

Not so long ago, I moved from VPS to a dedicated server, and I was suddenly faced with the question of transferring sites from the old server to the new one, namely, the quick creation of virtual hosts and databases. Of course, the ISPmanager control panel was in the appendage to the server, but in this case I did not like two things:
  • The panel does everything for you, but I want to upgrade my skill in the administration area.
  • I don’t like the way to create sites through the panel, namely the created paths to the folder with the site (/var/www/user_name/data/www/site.ru)

Because of this, I decided to configure everything with pens. I will not write about installing Apache and php, since there are a lot of materials on this topic both on Habré and on the Internet. We are more interested in the quick creation of a user, virtual host, and database. To whom it is interesting I ask in a tackle.

I decided to split the logic into two scripts.
  • Creates a user and adds sites in his folder. If there is no user, then it is created; if there is, then only the site is created.
  • The second script creates a database and a user for the database, assigning him privileges to this database.

A few conditions for scripts.
  • Both scripts generate default passwords.
  • Virtual host configs should be in / etc / apache2 / vhosts.
  • All actions should be performed only from under the superuser

Script to create a new virtual host (/ home / addsite)
#!/bin/bash
IP_ADDRESS="1.2.3.4"
APACHE2_DIR="/etc/apache2"
UID_ROOT=0
if [ "$UID" -ne "$UID_ROOT" ]; then
  echo "$0 - Requires root privileges"
  exit 1
fi
function is_user(){
    local check_user="$1";
    grep "$check_user:" /etc/passwd >/dev/null
    if [ $? -ne 0 ]; then
 #echo "NOT HAVE USER"
 return 0
    else
 #echo "HAVE USER"
 return 1
    fi
}
function generate_pass(){
    CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()-_=+\\|/"
    LENGTH="8"
    while [ "${n:=1}" -le "$LENGTH" ] ; do
	PASSWORD="$PASSWORD${CHARS:$(($RANDOM%${#CHARS})):1}"
        let n+=1
    done
    echo $PASSWORD
}
function is_yes(){
#TODO - add check 3-rd parameter for set default ansver (if press enter)
    while true
    do
 echo -n "Yes or No[Y/n]:"
 read  x
 if [ -z "$x" ]
 then
     return 0; #defaul answer: Yes
 fi
 case "$x" in
 y |Y |yes |Д |д |да ) return 0;;
 n |N |no |Н |н |нет ) return 1;;
# * ) ; # asc again
 esac
    done
}
function create_user(){
    local login="$1"
    local password="$2"
    `useradd -m -s /bin/bash $login`
    #set password
    echo -e "$password\n$password\n" | passwd $login >> /dev/null
}
USER_NAME=$1
echo -n "Check user name $USER_NAME: "
if( is_user "$USER_NAME" )then
    USER_PASSWORD="$(generate_pass)"
    echo "-----------------------------------"
    echo "User name    : $USER_NAME"
    echo "User password: $USER_PASSWORD"
    echo "-----------------------------------"
    echo -n "Continue? "
    if(! is_yes) then
        exit;
    fi
    echo "--- create user ---"
    create_user "$USER_NAME" "$USER_PASSWORD"
fi
if [ $# -eq 2 ]; then
    if [ "$2" != "delete" ]; then
        SITE_NAME=$2
        mkdir /home/$USER_NAME/$SITE_NAME
        mkdir /home/$USER_NAME/$SITE_NAME/www
        mkdir /home/$USER_NAME/$SITE_NAME/logs
        mkdir /home/$USER_NAME/$SITE_NAME/tmp
        mkdir /home/$USER_NAME/$SITE_NAME/cgi-bin
        hostConf="

        ServerName $SITE_NAME
        ServerAlias www.$SITE_NAME
        ServerAdmin webmaster@$SITE_NAME
        AddDefaultCharset utf-8
        AssignUserID ${USER_NAME} ${USER_NAME}
        DocumentRoot /home/$USER_NAME/$SITE_NAME/www
        CustomLog log combined
        ErrorLog /home/$USER_NAME/$SITE_NAME/logs/error.log
        DirectoryIndex index.php index.html
        ScriptAlias /cgi-bin/ /home/$USER_NAME/$SITE_NAME/cgi-bin
        
                SetHandler application/x-httpd-php
        
                SetHandler application/x-httpd-php-source
        
        php_admin_value upload_tmp_dir "/home/$USER_NAME/$SITE_NAME/tmp"
        php_admin_value session.save_path "/home/$USER_NAME/$SITE_NAME/tmp"
        php_admin_value open_basedir "/home/$USER_NAME/$SITE_NAME/www:."

        Options +Includes +ExecCGI
        php_admin_flag engine on

        "
        touch ${APACHE2_DIR}/vhosts/${SITE_NAME}.conf
        echo "$hostConf" >> ${APACHE2_DIR}/vhosts/${SITE_NAME}.conf
        touch //home/$USER_NAME/$SITE_NAME/www/index.php
        echo "" >> /home/$USER_NAME/$SITE_NAME/www/index.php
        chown $USER_NAME:$USER_NAME /home/$USER_NAME/$SITE_NAME/*
        service apache2 restart
    fi
fi;
#display information
echo "*****************************************"
echo "* Profit!"
echo "*****************************************"

In general, nothing complicated, at the very beginning we set the server ip address and the folder where we have the Apache settings. Do not forget to add the rights to execute the file
chmod -x /home/addsite

In order for Apache to pick up our configs at the end of the main configuration file, add
Include vhosts/

Run the script simply
/home/addsite user_name site.ru

The script will create a user, a virtual host and restart Apache. And of course he will not forget to show the password for the newly created user.
Database creation. Creating a database from phpMyAdmin bothered me a bit, you must first create a database, then a user and still remember to add database privileges to a new user, so we simplify our life (/ home / addbd).
#!/bin/bash
MYSQL_PASS="derev123blog"
UID_ROOT=0
if [ "$UID" -ne "$UID_ROOT" ]; then
  echo "$0 - Requires root privileges"
  exit 1
fi
function generate_pass(){
    CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()-_=+\\|/"
    LENGTH="8"
    while [ "${n:=1}" -le "$LENGTH" ] ; do
 PASSWORD="$PASSWORD${CHARS:$(($RANDOM%${#CHARS})):1}"
        let n+=1
    done
    echo $PASSWORD
}
function is_running(){
    local result="$(ps -A|grep $1|wc -l)"
    if [[ $result -eq 0 ]]; then
 return 1
    else
 return 0
    fi
}
if [ $# -eq 1 ]; then
    echo -n "Check MySQL status: "
    if(is_running mysqld)then
        echo "OK [Running]";
        DB_NAME=$1
        DB_PASSWORD="$(generate_pass)"
        mysql -uroot -p${MYSQL_PASS} --execute="create database ${DB_NAME};"
        mysql -uroot -p${MYSQL_PASS} --execute="GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_NAME}'@'localhost' IDENTIFIED by '${DB_PASSWORD}'  WITH GRANT OPTION;"
    else
        echo "Error: need start mysql daemon!"
        exit
    fi
fi;
#display information
echo "*****************************************"
echo "* Data base name: ${DB_NAME}"
echo "* Data base user: ${DB_NAME}"
echo "* User password: ${DB_PASSWORD}"
echo "* Profit!"
echo "*****************************************"

At the very beginning of the script, set the password for the root user from MySQL. Run by team
/home/addsite bd_name

A database and user will be created and data for connection will be displayed.
You can also add both files to the / bin directory to quickly call up command data
cp /home/addsite /bin/addsite
cp /home/addbd /bin/addbd

It seems like everyone. I hope this way of creating virtual hosts will simplify the life of users as well as me.

Also popular now: