The following script is part of WarCMS and licensed under the GNU Public License version 3. It is targeted for Apache version 2, and in daily use on servers running Debian GNU/Linux (Lenny)

Example

This example will create a working virtual host file in /etc/apache2/sites-available, enable it and then reload apache. The user running the command must have write-access to "/etc/apache2/sites-available", and eventually be in "/etc/sudoeres" in order to reload apache. If you are root, this is no problem. But the script was originally written as a helper to a daemon running as an unprivileged user, and it can be used by ordinary users provided that they have the appropriate rights. (see the comment by the end of the python-script about /etc/sudoers).

   # add_vhost.py --host www.jgaa.com --path /var/www/vsites/jgaa.com

/usr/local/bin/add_vhost.py

#! /usr/bin/python

from optparse import OptionParser
import os

def write_vhost_file(path, host, site, vhost):
     # Apache template
    template = """
        ServerAdmin webmaster@$host$
        ServerName $host$

        DocumentRoot $path$
        
                Options FollowSymLinks
                AllowOverride All
                Order allow,deny
                allow from all
        

        CustomLog /var/log/apache2/access_$host$ combined
"""
    # Replace macros
    template = template.replace('$path$', path);
    template = template.replace('$host$', host);
    template = template.replace('$vhost$', vhost);

    file = open(site, 'w')
    file.write(template)
    file.close()

def main():
    parser = OptionParser()
    parser.add_option("--path", dest="path",
                    help="Destination path")
    parser.add_option("--host",
                    dest="host",
                    help="Hostname for the site")
    parser.add_option("--vhost",
                    dest="vhost",
                    default="*",
                    help="Virtual host to bind to (Apache2 VirtualHost directive)")

    (options, args) = parser.parse_args()

    if (options.host is None) or (options.path is None):
        print "Must have destination-path and hostname!"
        exit(-1)

    #if not os.path.exists(options.path):
    site = '/etc/apache2/sites-available/' + options.host
    write_vhost_file(options.path, options.host, site, options.vhost)

    cmd = '/usr/sbin/a2ensite ' + '"' + options.host + '"'
    print 'Executing: ' + cmd
    os.system(cmd)
    print 'Reloading Apache config'

    # In order to use the sudo-command, the user that the server runs as
    # must have access to this command in /etc/sudoers
    # Example for the case where the server is running as 'www-data':
    #
    #   www-data ALL=NOPASSWD: /etc/init.d/apache2 reload

    os.system('sudo /etc/init.d/apache2 reload')

if __name__ == "__main__":
  main()