Skip to content

Instantly share code, notes, and snippets.

@shturm
Last active January 1, 2016 05:29
Show Gist options
  • Save shturm/8099085 to your computer and use it in GitHub Desktop.
Save shturm/8099085 to your computer and use it in GitHub Desktop.
Simple python script for adding sites in Ubuntu 12.04+. Given a <site-name> it: Creates /var/www/<site-name> folder, Sets 0777 permissions to the document root, Creates and enables a virtual host configuration, Reloads apache2 web server. Has option --mysql for creating a mysql database for the site
#!/usr/bin/python
import sys
import os
import getpass
from subprocess import call, PIPE, Popen
if (len(sys.argv) == 1 or sys.argv[1] == 'help'):
print "Usage is:\n\tsudo a2addsite <site-name> [--mysql]"
print "Parameters:"
print "\t--mysql - Brings interactive prompt for creating a database for the site"
exit(1)
if (os.geteuid() != 0):
print "You need run this script as root:\n\tsudo a2addsite <site-name>"
exit(1)
site = sys.argv[1]
docroot = '/var/www/'+site
hostsrecord = "\n127.0.0.1\t"+site
if '--mysql' in sys.argv:
mysqluser = raw_input('MySQL user <root>: ')
mysqlpass = getpass.getpass('MySQL password:')
mysqldb = raw_input('MySQL database to create <'+site+'>: ')
if not mysqluser: mysqluser = 'root'
if not mysqldb: mysqldb = site
sql = "CREATE SCHEMA IF NOT EXISTS "+site+";"
call(["mysql","-u",mysqluser,"-p"+mysqlpass,"-e",sql])
default = open('/etc/apache2/sites-available/default')
vhost = default.read().replace('/var/www',docroot).replace('localhost',site)
default.close()
vhostfile = open('/etc/apache2/sites-available/'+site,'w')
vhostfile.write(vhost)
vhostfile.close()
if not os.path.exists(docroot):
os.makedirs(docroot)
call(["a2ensite", site], stdout=PIPE)
call(["service", "apache2", "reload"], stdout=PIPE) # PIPE supresses output
with open("/etc/hosts", "r+") as hosts:
if hosts.read().find(hostsrecord) == -1:
hosts.write(hostsrecord)
os.chmod(docroot, 0777)
@TomSchillemans
Copy link

Cool, thanks for sharing this code. will be very helpfull!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment