📜 ⬆️ ⬇️

Creating virtual hosts in apache under Linux in Python

I develop websites and do all kinds of experiments and basic development on a local computer under Debian. In consequence of the fact that it was necessary to constantly create virtual hosts with pens, I had to set myself the goal of automating the process.
The first thing I went to the Internet in search of the necessary solution, which was to have simplicity and perform only 2 tasks: add a virtual host and delete it. It is convenient for me to use the console, so the application should have been a console. But all the options that I found had a large amount of unnecessary functionality, moreover, almost all of them provided a web interface, which I simply did not want to use.
As a result, goals were set:
- write your own simple script that created everything that I need;
- I chose python as the development language, since I've been looking for a reason to learn to write on it.

Update (09/08/11 8:25 PM): Considering the errors in the comments, I fixed the script a bit. Began to use optparse, reduced the use of .write.

As a result, I got a completely satisfying script under the cut .

#!/usr/bin/env python # -*- coding: utf-8 -*- ### #        ### import os, sys, re, shutil, string, pwd, grp, stat from optparse import OptionParser #   ,  ,    # ..          #     if os.getuid()!=0: sys.exit ("\033[31m     !\033[0m"); #   sname=os.path.basename(__file__); def main(): parser = OptionParser(usage="usage: %prog [options] [add|drop] domain", version="%prog 1.0") parser.add_option("-d", "--dir_site", default="/home/alen/domains/", metavar="/home/alen/domains/", help=u"  ."); parser.add_option("-a", "--apache_bin", default="/etc/init.d/apache2", metavar="/etc/init.d/apache2", help=u" apache  ."); parser.add_option("-c", "--apache_config_site", default="/etc/apache2/sites-enabled/", metavar="/etc/apache2/sites-enabled/", help=u" sites-enabled  apache   virtualhost."); parser.add_option("-t", "--host", default="/etc/hosts", metavar="/etc/hosts", help=u"  hosts     ."); parser.add_option("-i", "--ip", default="127.0.0.1", metavar="127.0.0.1", help=u"IP  "); parser.add_option("-e", "--a2ensite", default="a2ensite", metavar="a2ensite", help=u"enable an apache2 site / virtual host"); (options, args) = parser.parse_args(); if len(args)!=2 or not args[0] in {"add":1,"drop":2}: parser.error(sname+" -h"); return {"options":options,"args":args}; conf=main(); options=conf['options']; #          #        : dir_site stat_info = os.stat(options.dir_site); options.uid = stat_info.st_uid; options.gid = stat_info.st_gid; options.user = pwd.getpwuid(options.uid)[0]; options.group = grp.getgrgid(options.gid)[0]; #      def remove_string(filename, string): rst = []; with open(filename) as fd: t = fd.read(); for line in t.splitlines(): if line != string: rst.append(line); with open(filename, 'w') as fd: fd.write('\n'.join(rst)) fd.write('\n') def apache_site_config(name): file_name=options.apache_config_site+name; dir_site=options.dir_site+name; f = open(file_name,"w+"); print >> f, '<VirtualHost *:80>\n\n'+\ 'DocumentRoot '+ dir_site +'/www\n'+\ 'ServerAlias www.'+name+'\n'+\ 'ServerName '+name+'\n'+\ 'ScriptAlias /cgi-bin/ '+dir_site+'/www/cgi-bin/\n\n'+\ '<Directory "'+dir_site+'/www">\n'+\ '\tAllowOverride All\n'+\ '\tOrder Deny,Allow\n'+\ '\tAllow from all\n'+\ '\tOptions All\n'+\ '</Directory>\n\n'+\ '<Directory "'+dir_site+'/www/cgi-bin/">\n'+\ '\tAllowOverride None\n'+\ '\tOptions +ExecCGI -MultiViews +SymLinksIfOwnerMatch\n'+\ '\tOrder allow,deny\n'+\ '\tAllow from all\n'+\ '</Directory>\n\n'+\ '<IfModule dir_module>\n'+\ '\tDirectoryIndex index.php index.html index.cgi\n'+\ '</IfModule>\n\n'+\ '#SuexecUserGroup '+options.user+' '+options.group+'\n'+\ 'ErrorLog \"'+ dir_site +'/log/error.log\"\n'+\ 'CustomLog \"'+ dir_site +'/log/access.log\" combined\n'+\ 'LogLevel warn\n\n'+\ '</VirtualHost>'; f.close(); #    def add_domain(name): dir_site=options.dir_site+name; if os.path.exists(dir_site): sys.exit(" "+name+"      "+dir_site); elif os.path.exists(options.apache_config_site+name): sys.exit(options.apache_config_site+name+" -   !"); else: os.makedirs(dir_site+"/"); os.makedirs(dir_site+"/www/"); os.makedirs(dir_site+"/www/cgi-bin/"); os.makedirs(dir_site+"/log/"); f = open(dir_site+"/www/index.php","a+"); f.write('<?php\nphpinfo();'); f.close(); f = open(dir_site+"/www/cgi-bin/index.cgi","a+"); print >> f,'#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'+\ 'import cgitb\ncgitb.enable()\n\n'+\ 'print "Content-Type: text/plain;charset=utf-8"\n'+\ 'print\n\nprint "Hello World!"'; f.close(); os.system("chown -R "+options.user+":"+options.group+" "+dir_site); os.chmod(dir_site+"/www/cgi-bin/index.cgi", 0755); apache_site_config(name); f = open(options.host,"a+"); f.write("\n"+options.ip+"\t"+name+"\twww."+name); f.close(); f = open(dir_site+"/www/.htaccess","a+"); f.write("AddDefaultCharset UTF-8"); f.close(); os.system(options.a2ensite+" "+name); os.system(options.apache_bin+" restart"); sys.exit("\033[31m http://"+name+"  \033[0m"); pass; #    def drop_domain(name): dir_site=options.dir_site+name; if os.path.exists(dir_site): shutil.rmtree(dir_site); if os.path.exists(options.apache_config_site+name): os.unlink(options.apache_config_site+name); remove_string(options.host, options.ip+"\t"+name+"\twww."+name); os.system(options.apache_bin+" restart"); sys.exit("\033[31m   "+name+" !\033[0m"); pass; if conf["args"][0] in {"add":1,"drop":2} and \ re.compile('^[-\w.]{3,}$').match(conf["args"][1]): if conf["args"][0]=='add': add_domain(conf["args"][1]); else: drop_domain(conf["args"][1]); else: sys.exit("\033[31m \"" + conf["args"][0] + "\"  !\033[0m"); 

')
Script Notes

Due to the purpose of the script, it runs as root or through sudo.

Mini instruction for those who will not get to -help :
Usage: script [options] [add | drop] domain
The options change the settings for the script.

While adding or deleting a domain:
- a change is made in the hosts file, to enter information about the domain;
- in the directories transferred via dir_site the necessary files and folders for our domain are created;
- a file with the virtualhost configuration for apache is created in the directory specified in apache_config_site .

Taking advantage of the moment

Due to the fact that this is my first experience of writing a Python script, I really want to be extremely critical of my mistakes or the wrong approach (I will be especially grateful for the podzhopnik kick in the right direction).

Source: https://habr.com/ru/post/127996/


All Articles