baniol
1/19/2013 - 12:51 PM

create apache vhost for linux

create apache vhost for linux

#!/usr/bin/python
import os, sys, getopt, socket, stat
from pwd import getpwnam

# important: you have to manually put #@host@ into /etc/hosts file !
# important : you have to call the script from within the target directory !
 
SITES_DIR = "/etc/apache2/sites-available/"
SCRIPT_DIR = "/home/marcin/scripts/"
HOSTS_FILE = "/etc/hosts"
 
 
def main():
	try:
		opts, args = getopt.getopt(sys.argv[1:], "hd:u:t:s:", ["help", "domain="])
	except getopt.GetoptError, err:
		print str(err)
		usage()
		sys.exit(2)
 
	if len(opts) < 1:
		usage()
		sys.exit(2)
 
	for o, a in opts:
		if o in ("-h", "--help"):
			usage()
			sys.exit()
		if o in ("-d", "--domain"):
			domain = a

	# st = os.stat(SITES)
	# st = bool(st.st_mode & stat.S_IRGRP)
	# print st

	sitesperm = stat.S_IMODE(os.stat(SITES_DIR).st_mode)
	if(sitesperm < "777"):
		# os.chmod(0775, SITES)
		os.system('sudo chmod -R 777 %s' % SITES_DIR)
	# print filemode
	# sys.exit()

	hostsperm = stat.S_IMODE(os.stat(HOSTS_FILE).st_mode);
	if(hostsperm < "777"):
		os.system('sudo chmod 777 %s' % HOSTS_FILE);

	directory = os.getcwd()
	vhost_template = open(SCRIPT_DIR+'newvhost.conf').read()
	hosts_file = open(HOSTS_FILE).read();
 
	vhost = vhost_template.replace('@@dir@@', directory).replace('@@domain@@', domain)
	open(SITES_DIR + domain, 'w').write(vhost)
 
	hstring = "127.0.0.1 \t %s \n#@host@" % domain
	fhosts = hosts_file.replace('#@host@', hstring)
	open(HOSTS_FILE, 'w').write(fhosts)
	os.system('sudo a2ensite %s' % domain)
	os.system('sudo service apache2 restart')
 
def usage():
  print 'usage: [-d domain.com]'
 
if __name__=="__main__":
	main()