LinuxでPythonを使用してApacheで仮想ホストを作成する

私はサイトの開発に携わっており、Debianの下でローカルコンピューターであらゆる種類の実験と基本的な開発を行っています。 常にペンで仮想ホストを作成する必要があったという事実により、プロセスを自動化するという目標を設定する必要がありました。

まず、必要な解決策を求めてインターネットに移動しました。これは、シンプルであり、2つのタスクのみを実行することになっています。仮想ホストの追加と削除です。 コンソールを使用すると便利なため、アプリケーションはコンソールである必要があります。 しかし、私が見つけたすべてのオプションには大量の不要な機能があり、さらに、それらのほとんどすべてが、単に使用したくないWebインターフェイスを提供していました。

その結果、目標が設定されました。

-必要なものすべてを作成する独自のシンプルなスクリプトを作成します。

-開発言語としてpythonを選択しました。 私はそれについて書くことを学ぶ理由を長い間探していました。



更新(09/08/11 20:25):コメントにエラーがあるため、スクリプトはわずかに修正されました。 optparseの使用を開始し、.writeの使用を減らしました。



その結果、 猫の下で完全に満足できるスクリプトを得ました。



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







スクリプトノート


スクリプトの目的により、root`omとして、またはsudoを介して実行されます。



-helpにアクセスできない人のためのミニインストラクション:

使用法:スクリプト[オプション] [追加|ドロップ]ドメイン

オプションは、スクリプトの設定を変更します。



ドメインを追加または削除する場合:

-ドメインに関する情報を入力するために、hostsファイルに変更が加えられます。

-dir_siteを介して転送されたディレクトリに、ドメインに必要なファイルとフォルダーが作成されます。

-apacheの仮想ホスト設定を含むファイルは、 apache_config_siteで指定されたディレクトリに作成されます



瞬間をつかむ


Pythonスクリプトを書くのはこれが私の最初の経験であるという事実のために、私は自分の間違いや間違ったアプローチについて可能な限り批判的になりたいと思います(特に正しい方向へのキックキックに感謝します)。



All Articles