ronisaha
7/14/2014 - 6:16 AM

Create vHost Ubuntu Lamp-Server (bash and python)

Create vHost Ubuntu Lamp-Server (bash and python)

#! /usr/bin/python

from sys import argv
from os.path import exists
from os import makedirs
from os import symlink
from os import system
import getopt
import re

#
#   Show Usage, Output to STDERR
#
def show_usage():
	print """
	Create a new vHost in Ubuntu Server
	Assumes /etc/apache2/sites-available and /etc/apache2/sites-enabled setup used

	    -d    DocumentRoot - i.e. /var/www/yoursite
	    -h    Help - Show this menu.
	    -s    ServerName - i.e. example.com or sub.example.com
	"""
	exit(1)

#
#   Output vHost skeleton, fill with userinput
#   To be outputted into new file
#
def create_vhost(documentroot, servername, baseName):
	out = """<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName %s
    ServerAlias %s %s
    
    DocumentRoot %s

    <Directory %s>
        Options -Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/%s-error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/%s-access.log combined

</VirtualHost>""" % (servername, "www."+servername, baseName, documentroot, documentroot, servername, servername)
	return out

#Parse flags, fancy python way. Long options also!
try:		
	opts, args = getopt.getopt(argv[1:], "hd:s:", ["help", "document-root=", 'server-name='])
except getopt.GetoptError, err:
	print str(err)
	show_usage()

#Sanity check - make sure there are arguments
if opts.__len__() == 0:
	show_usage()

documentRoot = None
serverName = None

#Get values from flags
for option, value in opts:
	if option in ('-h', '--help'):
		show_usage()
	elif option in ('-d', '--document-root'):
		documentRoot = value
	elif option in ('-s', '--server-name'):
		serverName = value
	else:
		print "Unknown parameter used"
		show_usage()

if exists(documentRoot) == False:
	makedirs(documentRoot, 0755)
	#chown USER:USER $DocumentRoot #POSSIBLE IMPLEMENTATION, new flag -u ?
	#from pwd import getpwnam  -> inspect: getpwnam('someuser')

if exists('%s/%s.conf' % (documentRoot, serverName)):
	print 'vHost already exists. Aborting'
   	show_usage()
else:
	target = open('/etc/apache2/sites-available/%s.conf' % serverName, 'w')
	target.write(create_vhost(documentRoot, serverName, re.sub('(.dev|.local)$', '', serverName)))
	target.close()
	
	srcLink = '/etc/apache2/sites-available/%s.conf' % serverName
	destLink = '/etc/apache2/sites-enabled/%s.conf' % serverName
	symlink(srcLink, destLink)
	
	system('service apache2 reload')
#! /bin/bash

# The MIT License (MIT)
# Copyright (c) 2014 Roni Saha<roni.cse@gmail.com>

# May need to run this as sudo!
# Copy it in global path (like /usr/local/bin) and run command 'vhost' from anywhere, using sudo.

#
#   Show Usage, Output to STDERR
#
function show_usage {
cat <<- _EOF_

Create a new vHost in Ubuntu Server
Assumes /etc/apache2/sites-available and /etc/apache2/sites-enabled setup used

    -d    DocumentRoot - i.e. /var/www/yoursite
    -h    Help - Show this menu.
    -s    ServerName - i.e. example.com or sub.example.com
    -a    ServerAlias - i.e. www.example.com
    
_EOF_
exit 1
}

#Make sure the script executed as root
if [[ $EUID -ne 0 ]]; then
  echo "You must be a root user, or run as: sudo vhost" 2>&1
  show_usage
fi

#
#   Output vHost skeleton, fill with userinput
#   To be outputted into new file
#
function create_vhost {
cat <<- _EOF_
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName $ServerName
    ServerAlias $ServerAlias $baseName.*.xip.io www.$baseName.*.xip.io

    DocumentRoot $DocumentRoot

    <Directory $DocumentRoot>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/$ServerName-error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog \${APACHE_LOG_DIR}/$ServerName-access.log combined


</VirtualHost>
_EOF_
}

#Sanity Check - are there one arguments with 1 values?
if [ $# -lt 2 ]; then
	show_usage
fi

#Parse flags
while getopts "d:s:a:" OPTION; do
    case $OPTION in
        h)
            show_usage
            ;;
        d)
 	    DocumentRootGiven=$OPTARG
            ;;
        s)
            ServerName=$OPTARG
            ;;
	a)
	    ServerAlias=$OPTARG
	    ;;
        *)
            show_usage
            ;;
    esac
done


if [[ -z $ServerName ]]
then
	echo "You must provide the server name parameter. Aborting"
	show_usage
fi

if [[ -z $ServerAlias ]]
then
     ServerAlias="www.$ServerName"
fi

if [[ -z $DocumentRootGiven ]]
then
    DocumentRoot=$(pwd)
else
    DocumentRoot=$(readlink -f $DocumentRootGiven)
fi

if [[ -z $DocumentRoot ]]
then
	echo "Invalid document root given. Aborting"
        show_usage
fi


if [ ! -d $DocumentRoot ]; then 
    mkdir -p $DocumentRoot
    #chown USER:USER $DocumentRoot #POSSIBLE IMPLEMENTATION, new flag -u ?
fi

baseName=${ServerName%.dev}
baseName=${baseName%.local}

if [ -f "/etc/apache2/sites-available/${ServerName}.conf" ]; then
    echo 'Virtual Host already exists. Aborting'
    show_usage
else
    create_vhost > /etc/apache2/sites-available/${ServerName}.conf
    ln -s /etc/apache2/sites-available/${ServerName}.conf /etc/apache2/sites-enabled/${ServerName}.conf
    sed -i "2i127.0.0.1 $ServerName $ServerAlias" /etc/hosts
    echo "Virtual host has been created."
    service apache2 reload 
fi