Apache virtual host creation script in Python

In this article, I’ve put a script in Python to create virtual hosts in Apache on Debian (the same script can be used on other operating systems to linux, after taking a few changes in the settings).
Now, let’s try to understand what you need to do to create virtual hosts.
Article: show sponsor personnel training in Moscow. Please visit their website.
1. it is necessary to determine which directory will have the folder with the project (website).
2. In the folder configured virtualhost (/etc/apache2/sites-enabled/) to create a file with a description of the virtual host: the name, the place of its location, you can also specify other settings, such as log file path errors or requests for the virtual host. An example of such a file:

  1. DocumentRoot /home/user/domains/mydomain.local/www
  2. ServerAlias www.mydomain.local
  3. ServerName mydomain.local
  4. ScriptAlias /cgi-bin/ /home/user/domains/mydomain.local/www/cgi-bin/
  5. AllowOverride All
  6. Order Deny,Allow
  7. Allow from all
  8. Options All
  9. AllowOverride None
  10. Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
  11. Order allow,deny
  12. Allow from all
  13. DirectoryIndex index.php index.html index.cgi
  14. #SuexecUserGroup user user
  15. ErrorLog “/home/user/domains/mydomain.local/log/error.log”
  16. CustomLog “/home/user/domains/mydomain.local/log/access.log” combined
  17. LogLevel warn
In this configuration file, you should have been clear that they belong to the mydomain.local, there are alias www.mydomain.local. On this query request is made to the directory/home/user/domains/mydomain.local/www, and index files are files: index.php index.html index.cgi. The log files /home/user/domains/mydomain.local/log/error.log
and /home/user/domains/mydomain.local/log/access.log, and the directory for CGI scripts is/home/user/domains/mydomain.local/www/cgi-bin/. Additional options can be found in official documentation.
3. Now you need to convey to our computer, that domain mydomain.local leads to our ip address and later processed using Apache.
If your domain should be visible from the network, you must configure DNS (a topic for another article), if we only need to see the virtualhost, then you must specify the/etc/hosts file to which ip should join our domain, by default you can attach to the IP

  1. mydomain.local www.mydomain.local


Apache virtual host creation script in Python
All the above steps have been described in the script published below.
To use it, you must save the script (for convenience, you can place it in a directory such as/usr/local/sbin for example the name ad-da) and set the rights to run the script, chmod + x/usr/local/sbin/ad-da

  1. cd /usr/local/sbin/
  2. wget http://4debian.info/download-script/ad-da
  3. chmod +x ad-da
  4. nano ad-da


Change the default settings on the:

  1. parser.add_option(“-d”, “–dir_site”, default=”/home/valualit/domains/”,
  2. metavar=”/home/valualit/domains/”, help=u”Директория для домена.”);
Replace/home/user/domains/in the directory where the folder will be placed with our domains. Other changes made as necessary.
The script is only run as root or with sudo but all project files (website) created by default accept the right of the parent directory (in this example,/home/user/domains/) so the files will easily be edited by the owner of the directory.
-Same script creates all the standard files to instantly verify script and Apache.
After you add or remove virtualhost Apache restarts automatically through a script.

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ###
  4. # Скрипт предназначен для легкого управления локальными доменами
  5. ###
  6. import os, sys, re, shutil, string, pwd, grp, stat
  7. from optparse import OptionParser
  8. # Проверяем права администратора, если нет, то выводим предупреждение
  9. # т.к. правка системных файлов не возможно без соответствующих прав доступа
  10. # и приведет к ошибкам
  11. if os.getuid()!=0:
  12. sys.exit (“33[31mСкрипт должен работать с правами администратора!33[0m”);
  13. # Название скрипта
  14. sname=os.path.basename(__file__);
  15. def main():
  16. parser = OptionParser(usage=”usage: %prog [options] [add|drop] domain”,
  17. version=”%prog 1.0″)
  18. parser.add_option(“-d”, “–dir_site”, default=”/home/valualit/domains/”,
  19. metavar=”/home/valualit/domains/”, help=u”Директория для домена.”);
  20. parser.add_option(“-a”, “–apache_bin”, default=”/etc/init.d/apache2″,
  21. metavar=”/etc/init.d/apache2″, help=u”Бинарник apache для рестарта.”);
  22. parser.add_option(“-c”, “–apache_config_site”,
  23. default=”/etc/apache2/sites-available/”, metavar=”/etc/apache2/sites-available/”,
  24. help=u”Директория sites-available от apache для настроек virtualhost.”);
  25. parser.add_option(“-t”, “–host”, default=”/etc/hosts”, metavar=”/etc/hosts”,
  26. help=u”Системный файл hosts для внесения информации о домене.”);
  27. parser.add_option(“-i”, “–ip”, default=”″, metavar=”″,
  28. help=u”IP для сайта”);
  29. parser.add_option(“-e”, “–a2ensite”, default=”a2ensite”, metavar=”a2ensite”,
  30. help=u”enable an apache2 site / virtual host”);
  31. (options, args) = parser.parse_args();
  32. if len(args)!=2 or not args[0] in {“add”:1,”drop”:2}:
  33. parser.error(sname+” -h”);
  34. return {“options”:options,”args”:args};
  35. conf=main();
  36. options=conf[‘options’];
  37. # Получаем группу и пользователя права которого будут для папки
  38. # Возьмем их из папки в которую все сложим: dir_site
  39. stat_info = os.stat(options.dir_site);
  40. options.uid = stat_info.st_uid;
  41. options.gid = stat_info.st_gid;
  42. options.user = pwd.getpwuid(options.uid)[0];
  43. options.group = grp.getgrgid(options.gid)[0];
  44. # Функция удаления строки из файла
  45. def remove_string(filename, string):
  46. rst = [];
  47. with open(filename) as fd:
  48. t = fd.read();
  49. for line in t.splitlines():
  50. if line != string:
  51. rst.append(line);
  52. with open(filename, ‘w’) as fd:
  53. fd.write(‘n’.join(rst))
  54. fd.write(‘n’)
  55. def apache_site_config(name):
  56. file_name=options.apache_config_site+name;
  57. dir_site=options.dir_site+name;
  58. f = open(file_name,”w+”);
  59. print >> f, ‘<VirtualHost *:80>nn’+
  60. ‘DocumentRoot ‘+ dir_site +’/wwwn’+
  61. ‘ServerAlias www.’+name+’n’+
  62. ‘ServerName ‘+name+’n’+
  63. ‘ScriptAlias /cgi-bin/ ‘+dir_site+’/www/cgi-bin/nn’+
  64. ‘<Directory “‘+dir_site+’/www”>n’+
  65. ‘tAllowOverride Alln’+
  66. ‘tOrder Deny,Allown’+
  67. ‘tAllow from alln’+
  68. ‘tOptions Alln’+
  69. ‘</Directory>nn’+
  70. ‘<Directory “‘+dir_site+’/www/cgi-bin/”>n’+
  71. ‘tAllowOverride Nonen’+
  72. ‘tOptions +ExecCGI -MultiViews +SymLinksIfOwnerMatchn’+
  73. ‘tOrder allow,denyn’+
  74. ‘tAllow from alln’+
  75. ‘</Directory>nn’+
  76. ‘<IfModule dir_module>n’+
  77. ‘tDirectoryIndex index.php index.html index.cgin’+
  78. ‘</IfModule>nn’+
  79. ‘#SuexecUserGroup ‘+options.user+’ ‘+options.group+’n’+
  80. ‘ErrorLog “‘+ dir_site +’/log/error.log”n’+
  81. ‘CustomLog “‘+ dir_site +’/log/access.log” combinedn’+
  82. ‘LogLevel warnnn’+
  83. ‘</VirtualHost>’;
  84. f.close();
  85. # Функция добавления домена
  86. def add_domain(name):
  87. dir_site=options.dir_site+name;
  88. if os.path.exists(dir_site):
  89. sys.exit(“Сайт “+name+” не может быть записан в “+dir_site);
  90. elif os.path.exists(options.apache_config_site+name):
  91. sys.exit(options.apache_config_site+name+” – Занят конфигурационный файл!”);
  92. else:
  93. os.makedirs(dir_site+”/”);
  94. os.makedirs(dir_site+”/www/”);
  95. os.makedirs(dir_site+”/www/cgi-bin/”);
  96. os.makedirs(dir_site+”/log/”);
  97. f = open(dir_site+”/www/index.php”,”a+”);
  98. f.write(‘<?phpnphpinfo();’);
  99. f.close();
  100. f = open(dir_site+”/www/cgi-bin/index.cgi”,”a+”);
  101. print >> f,’#!/usr/bin/env pythonn# -*- coding: utf-8 -*-nn’+
  102. ‘import cgitbncgitb.enable()nn’+
  103. ‘print “Content-Type: text/plain;charset=utf-8″n’+
  104. ‘printnnprint “Hello World!”‘;
  105. f.close();
  106. os.system(“chown -R “+options.user+”:”+options.group+” “+dir_site);
  107. os.chmod(dir_site+”/www/cgi-bin/index.cgi”, 0755);
  108. apache_site_config(name);
  109. f = open(options.host,”a+”);
  110. f.write(“n”+options.ip+”t”+name+”twww.”+name);
  111. f.close();
  112. f = open(dir_site+”/www/.htaccess”,”a+”);
  113. f.write(“AddDefaultCharset UTF-8”);
  114. f.close();
  115. os.system(options.a2ensite+” “+name);
  116. os.system(options.apache_bin+” restart”);
  117. sys.exit(“33[31mДомен http://”+name+” успешно создан33[0m”);
  118. pass;
  119. # Функция удаления домена
  120. def drop_domain(name):
  121. dir_site=options.dir_site+name;
  122. if os.path.exists(dir_site):
  123. shutil.rmtree(dir_site);
  124. if os.path.exists(options.apache_config_site+name):
  125. os.unlink(options.apache_config_site+name);
  126. remove_string(options.host, options.ip+”t”+name+”twww.”+name);
  127. os.system(options.apache_bin+” restart”);
  128. sys.exit(“33[31mУпоминания о домене “+name+” удалены!33[0m”);
  129. pass;
  130. if conf[“args”][0] in {“add”:1,”drop”:2} and
  131. re.compile(‘^[-w.]{3,}$’).match(conf[“args”][1]):
  132. if conf[“args”][0]==’add’:
  133. add_domain(conf[“args”][1]);
  134. else:
  135. drop_domain(conf[“args”][1]);
  136. else:
  137. sys.exit(“33[31mКоманды “” + conf[“args”][0] + “” не существует!33[0m”);
And as it should enclose a few screenshots.