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)


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).

   # --host --path /var/www/vsites/


#! /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')

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

    (options, args) = parser.parse_args()

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

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

    cmd = '/usr/sbin/a2ensite ' + '"' + + '"'
    print 'Executing: ' + 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__":