This program allow to update a dns from a dynamic ip. It use nsupdate to add and delete any record from a dns zone. It update it securly thanks a key you set before. Currently it support only anames.
1 #!/usr/local/bin/python2.4
2 #
3 # Copyright (c) 2007 Benoit Chesneau <benoit@bchesneau.info>
4 #
5 # Permission to use, copy, modify, and distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 #
9 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 #
17 # Description :
18 # This program allow to update a dns from a dynamic ip. It use nsupdate to add
19 # and delete any record from a dns zone. It update it securly thanks a key you
20 # set before. Currently it support only anames.
21 #
22 # It require to create a configuration file /etc/ddns.conf or ~/.ddns.conf :
23 # add a zone like this :
24 # [domain1]
25 # key=<path to your private key>
26 # server = <name of dns>
27 # zone = <zone name>
28 # anames = <anames you want to add/update>
29 #
30 # Add as any zone you want by creating section [domainXX] in your
31 # configuration file.
32 #
33 #
34 # For more information on setting your dns ypu can go here :
35 # * nsupdate: Painless Dynamic DNS: http://linux.yyz.us/nsupdate/
36 # * A DDNS Server Using BIND and Nsupdate : http://www.oceanwave.com/technical-resources/unix-admin/nsupdate.html
37 # * DynDNS et Subzone ARPA : http://wiki.gcu.info/doku.php?id=unix:dyndns&s=bind
38
39
40 import re
41 import urllib
42 import ConfigParser
43 import os
44 import time
45
46 checkip_urls = (
47 (r'Current IP Address:\s(?P<ip>[^<]*)', 'http://checkip.dyndns.org/'),
48 (r'Current Address:\s(?P<ip>.*)$', 'http://ipdetect.dnspark.com/'),
49 )
50
51 rIP=re.compile("(\d{1,3}(\.\d{1,3}){3})(?!/\d+)")
52 cmd = '/usr/sbin/nsupdate'
53
54 def get_ip():
55 """
56 For now we get dynamic ip only from web.
57 TODO: add detection from interface and router
58 """
59 f = None;
60 ip=None
61 for u in checkip_urls:
62 pat = re.compile(u[0]);
63 try:
64 f = urllib.urlopen(u[1])
65 except:
66 continue
67
68 if f:
69 for line in f.readlines():
70 match = pat.search(line)
71 if match is not None:
72 ip=match.group('ip')
73 if rIP.search(ip):
74 return ip
75
76 return ip
77
78 def get_conffile():
79 conffiles = ("~/.ddns.conf", "/etc/ddns.conf",)
80 for c in conffiles:
81 path = os.path.expanduser(c)
82 if os.path.exists(path):
83 return path
84 return None
85
86 def get_conf():
87 domains = []
88 config = ConfigParser.ConfigParser()
89 config.read(get_conffile())
90 for section in config.sections():
91 if section.startswith('domain'):
92 anames = config.get(section, 'anames').split(',')
93 domains.append({
94 'key_path': config.get(section, 'key'),
95 'anames': [aname.strip() for aname in anames],
96 'server': config.get(section, 'server').strip(),
97 'zone': config.get(section, 'zone').strip(),
98 })
99 return domains
100
101 def nsupdate(domain, ip):
102 tmp_path = '/var/tmp/.ddns_%s.txt' % domain['server']
103 aname_str=""
104 for aname in domain['anames']:
105 if aname_str != "": aname_str="\n"
106 aname_str+="""update delete %(aname)s A
107 update add %(aname)s 60 A %(ip)s
108 show
109 send""" % {
110 'aname': aname,
111 'ip': ip,
112 }
113 tmp_str = """server %(server)s
114 zone %(zone)s
115 %(aname_str)s
116 """ % {
117 'server': domain['server'],
118 'zone': domain['zone'],
119 'aname_str': aname_str,
120
121
122 }
123
124 fdomain = open(tmp_path, 'w+')
125 fdomain.write(tmp_str)
126 fdomain.close()
127 cmd_str = "%s -k %s -v %s" % (cmd,domain['key_path'],tmp_path)
128 os.system(cmd_str)
129
130 def update_dns():
131 ip_path = "/var/tmp/.ddns_ip"
132 while True:
133 ip=get_ip()
134 if os.path.exists(ip_path):
135 f = open(ip_path, 'r')
136 old_ip = f.readline()
137 f.close()
138 else:
139 old_ip = ""
140
141 if ip != old_ip:
142 f=open(ip_path, 'w')
143 f.write(ip)
144 f.close()
145 domains = get_conf()
146 if not domains:
147 print 'no domain configured yet.'
148 os._exit(1)
149 for domain in domains:
150 nsupdate(domain, ip)
151
152 time.sleep(60)
153
154
155 ip=get_ip()
156 domains = get_conf()
157 if not domains:
158 print 'no domain configured yet.'
159 os._exit(1)
160
161 try:
162 if os.fork() > 0: os._exit(0) # exit father...
163 except OSError, error:
164 print 'fork #1 failed: %d (%s)' % (error.errno, error.strerror)
165 os._exit(1)
166
167 os.chdir('/')
168 os.setsid()
169 os.umask(0)
170
171 try:
172 pid = os.fork()
173 if pid > 0:
174 f = open('/tmp/ddns.pid', 'w')
175 f.write("%i" % pid)
176 f.close()
177 os._exit(0)
178 except OSError, error:
179 print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror)
180 os._exit(1)
181
182 update_dns()
version "minimaliste"
1 from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
2
3 class MyServer(BaseHTTPRequestHandler):
4 def do_GET(self):
5 self.send_response(200, 'OK')
6 self.send_header('Content-type', 'text/html')
7 self.end_headers()
8 self.wfile.write( "hello" )
9
10 @staticmethod
11 def serve_forever(port):
12 HTTPServer(('', port), MyServer).serve_forever()
13
14 if __name__ == "__main__":
15 MyServer.serve_forever(8080)
Ce script fonctionne comme la commande UNIX "du", mais pour les fichiers : il calcule la taille totale des fichiers donnés et l'affiche en o, Ko, Mo et Go.
1 import os
2 import sys
3
4 if len(sys.argv) == 1:
5 print "Usage : %s files"%(sys.argv[0])
6 sys.exit(0)
7
8 sizes_sum = 0.0
9 for file in sys.argv[1:]:
10 if not os.path.isfile(file):
11 print "%s is not a regular file"%(file)
12 sys.exit(1)
13 sizes_sum = sizes_sum + os.path.getsize(file)
14
15 print "%d o"%(int(sizes_sum))
16 print "%0.02f Ko"%(sizes_sum/1024)
17 print "%0.02f Mo"%(sizes_sum/1024/1024)
18 print "%0.02f Go"%(sizes_sum/1024/1024/1024)
Ouverture et Enregistrement XML en Python
1 import xml.dom
2 import xml.dom.ext.reader.Sax2
3 import xml.dom.ext
4
5 # Ouverture du fichier XML
6 f = open('fichier.xml'), 'r')
7 reader = xml.dom.ext.reader.Sax2.Reader()
8 dom = reader.fromStream(f)
9
10 # Manipulation du DOM
11 # ...
12
13 # Enregistrement
14 xml.dom.ext.Print(dom, open('fichier.xml', 'w'))
15 # Enregistrement indenté
16 xml.dom.ext.PrettyPrint(dom, open('fichier.xml', 'w'))
Exemple d'utilisation Accents.clean("mämé") == "mame"
1 class Accents:
2 __reptable = {}
3
4 __corresp = [
5 (u"A", [0x00C0,0x00C1,0x00C2,0x00C3,0x00C4,0x00C5,0x0100,0x0102,0x0104]),
6 (u"AE", [0x00C6]),
7 (u"a", [0x00E0,0x00E1,0x00E2,0x00E3,0x00E4,0x00E5,0x0101,0x0103,0x0105]),
8 (u"ae", [0x00E6]),
9 (u"C", [0x00C7,0x0106,0x0108,0x010A,0x010C]),
10 (u"c", [0x00E7,0x0107,0x0109,0x010B,0x010D]),
11 (u"D", [0x00D0,0x010E,0x0110]),
12 (u"d", [0x00F0,0x010F,0x0111]),
13 (u"E", [0x00C8,0x00C9,0x00CA,0x00CB,0x0112,0x0114,0x0116,0x0118,0x011A]),
14 (u"e", [0x00E8,0x00E9,0x00EA,0x00EB,0x0113,0x0115,0x0117,0x0119,0x011B]),
15 (u"G", [0x011C,0x011E,0x0120,0x0122]),
16 (u"g", [0x011D,0x011F,0x0121,0x0123]),
17 (u"H", [0x0124,0x0126]),
18 (u"h", [0x0125,0x0127]),
19 (u"I", [0x00CC,0x00CD,0x00CE,0x00CF,0x0128,0x012A,0x012C,0x012E,0x0130]),
20 (u"i", [0x00EC,0x00ED,0x00EE,0x00EF,0x0129,0x012B,0x012D,0x012F,0x0131]),
21 (u"IJ", [0x0132]),
22 (u"ij", [0x0133]),
23 (u"J", [0x0134]),
24 (u"j", [0x0135]),
25 (u"K", [0x0136]),
26 (u"k", [0x0137,0x0138]),
27 (u"L", [0x0139,0x013B,0x013D,0x013F,0x0141]),
28 (u"l", [0x013A,0x013C,0x013E,0x0140,0x0142]),
29 (u"N", [0x00D1,0x0143,0x0145,0x0147,0x014A]),
30 (u"n", [0x00F1,0x0144,0x0146,0x0148,0x0149,0x014B]),
31 (u"O", [0x00D2,0x00D3,0x00D4,0x00D5,0x00D6,0x00D8,0x014C,0x014E,0x0150]),
32 (u"o", [0x00F2,0x00F3,0x00F4,0x00F5,0x00F6,0x00F8,0x014D,0x014F,0x0151]),
33 (u"OE", [0x0152]),
34 (u"oe", [0x0153]),
35 (u"R", [0x0154,0x0156,0x0158]),
36 (u"r", [0x0155,0x0157,0x0159]),
37 (u"S", [0x015A,0x015C,0x015E,0x0160]),
38 (u"s", [0x015B,0x015D,0x015F,0x01610,0x017F]),
39 (u"T", [0x0162,0x0164,0x0166]),
40 (u"t", [0x0163,0x0165,0x0167]),
41 (u"U", [0x00D9,0x00DA,0x00DB,0x00DC,0x0168,0x016A,0x016C,0x016E,0x0170,0x172]),
42 (u"u", [0x00F9,0x00FA,0x00FB,0x00FC,0x0169,0x016B,0x016D,0x016F,0x0171]),
43 (u"W", [0x0174]),
44 (u"w", [0x0175]),
45 (u"Y", [0x00DD,0x0176,0x0178]),
46 (u"y", [0x00FD,0x00FF,0x0177]),
47 (u"Z", [0x0179,0x017B,0x017D]),
48 (u"z", [0x017A,0x017C,0x017E])
49 ]
50 for __repchar,__codes in __corresp :
51 for __code in __codes :
52 __reptable[__code] = __repchar
53
54 @staticmethod
55 def clean(s):
56 """ enleve les accents de 's' (unicode ou utf8), et renvoi de l'unicode
57 (marche pour maj et minuscules !!!)
58 """
59 if isinstance(s,str) :
60 s = unicode(s,"utf8","replace")
61 return s.translate(Accents.__reptable)
Convertit n'importe quelle chaîne de caractères Unicode en chaîne de caractère ASCII : supprime les accents et remplace les lettres spéciales par des caractères ASCII semblables.
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # This source code is distributed under GNU GPL v2 license
5 # written by Victor Stinner <victor.stinner AT haypocalc.com>
6 # http://www.haypocalc.com/
7 # creatied: 2006-08-14 -- last change: 2007-08-17
8
9 # Convert any unicode string to ASCII string:
10 # - Remove diacriticals
11 # - Replace special letter with similar ASCII character (similar glyph)
12 #
13 # Support greek, cyrillic, some latin letters and some signs.
14
15 from unicodedata import normalize
16
17 UNICODE_TO_ASCII = {
18 # Latin letters
19 u"Æ": u"AE", # U+00C6 (latin capital ligature ae)
20 u"Ø": u"O", # U+00D8 (latin capital letter o with stroke)
21 u"ß": u"ss", # U+00DF (latin small letter sharp s)
22 u"æ": u"ae", # U+00E6 (latin small ligature ae)
23 u"ø": u"o", # U+00F8 (latin small letter o with stroke)
24 u"?": u"l", # U+0142 (latin small letter l with stroke)
25 u"Œ": u"OE", # U+0152 (latin capital ligature oe)
26 u"œ": u"oe", # U+0153 (latin small ligature oe)
27
28 # Various signs
29 u"¡": u"!", # U+00A1 (inverted exclamation mark)
30 u"©": u"(c)", # U+00A9 (copyright sign)
31 u"«": u'"', # U+00AB (left-pointing double angle quotation mark)
32 u"®": u"(r)", # U+00AE (registred sign)
33 u"²": u"2", # U+00B2 (superscript two)
34 u"»": u'"', # U+00BB (right-pointing double angle quotation mark)
35 u"?": u"/", # U+2044 (fraction slash)
36
37 # Greek
38 u"?": u"A", # U+0391 (capital alpha)
39 u"?": u"B", # U+0392 (capital beta)
40 u"?": u"E", # U+0395 (capital epsilon)
41 u"?": u"Z", # U+0396 (capital zeta)
42 u"?": u"H", # U+0397 (capital eta)
43 u"?": u"O", # U+0398 (captial theta)
44 u"?": u"I", # U+0399 (capital iota)
45 u"?": u"K", # U+039A (capital kappa)
46 u"?": u"M", # U+039C (capital mu)
47 u"?": u"N", # U+039D (capital nu)
48 u"?": u"O", # U+039F (capital omicron)
49 u"?": u"P", # U+03A1 (capital rho)
50 u"?": u"T", # U+03A4 (capital tau)
51 u"?": u"Y", # U+03A5 (capital upsilon)
52 u"?": u"X", # U+03A7 (capital chi)
53 u"?": u"a", # U+03B1 (small alpha)
54 u"?": u"b", # U+03B2 (small beta)
55 u"?": u"y", # U+03B2 (small gamma)
56 u"?": u"e", # U+03B5 (small espilon)
57 u"?": u"n", # U+03B7 (small eta)
58 u"?": u"o", # U+03BF (small omicron)
59 u"?": u"p", # U+03C1 (small rho)
60 u"?": u"v", # U+03C1 (small upsilon)
61
62 # Cyrillic
63 u"?": u"I", # U+0406 (capital byelorussian-ukrainian i)
64 u"?": u"J", # U+0408 (capital je)
65 u"?": u"B", # U+0412 (capital ve)
66 u"?": u"E", # U+0415 (capital ie)
67 u"?": u"N", # U+0418 (capital i)
68 u"?": u"3", # U+0417 (capital ze)
69 u"?": u"K", # U+041A (capital ka)
70 u"?": u"M", # U+041C (capital em)
71 u"?": u"H", # U+041D (capital en)
72 u"?": u"O", # U+041E (capital o)
73 u"?": u"P", # U+0420 (capital er)
74 u"?": u"C", # U+0421 (capital es)
75 u"?": u"T", # U+0422 (capital te)
76 u"?": u"Y", # U+0423 (capital u)
77 u"?": u"X", # U+0425 (capital ha)
78 u"?": u"R", # U+042F (capital ya)
79 u"?": u"a", # U+0430 (small a)
80 u"?": u"b", # U+0432 (small ve)
81 u"?": u"e", # U+0435 (small ie)
82 u"?": u"3", # U+0437 (small ze)
83 u"?": u"k", # U+043A (small ka)
84 u"?": u"m", # U+043C (small em)
85 u"?": u"h", # U+043D (small en)
86 u"?": u"o", # U+043E (small o)
87 u"?": u"p", # U+0440 (small er)
88 u"?": u"c", # U+0441 (small es)
89 u"?": u"T", # U+0442 (small te)
90 u"?": u"y", # U+0443 (small u)
91 u"?": u"x", # U+0445 (small ha)
92 u"?": u"R", # U+044F (small ya)
93 u"?": u"i", # U+0456 (small byelorussian-ukrainian i)
94 u"?": u"j", # U+0458 (small je)
95 }
96
97 def unicode2ascii(text, replace=False):
98 """
99 Convert an unicode string (type 'unicode') to ascii string (type 'str').
100 Try to keep same visual result.
101
102 You can specify an ASCII character to replace non-ASCII character
103 in 'replace' argument (eg. replace='?').
104
105 >>> unicode2ascii(unicode("¡ Hé hø « español » ! Pythøn", "UTF-8"))
106 '! He ho " espanol " ! Python'
107 >>> unicode2ascii(unicode("L'œuf de læticia", "UTF-8"))
108 "L'oeuf de laeticia"
109 >>> unicode2ascii(unicode("????????????????????????????", "UTF-8"), u'?')
110 'IEOAB??EZHOIK?NM?OYanay?e?n?'
111 >>> unicode2ascii(unicode("??????????????????????????????????????????", "UTF-8"), u'?')
112 'EE??IIJKN?BE3NKMHOPCTYXabe3mho?pcTyxeeiijk'
113 """
114 assert isinstance(text, unicode)
115 if replace:
116 if isinstance(replace, str):
117 replace = unicode(replace, "latin-1")
118 if not isinstance(replace, unicode) \
119 or len(replace) != 1 \
120 or not (32 <= ord(replace) <= 127):
121 raise ValueError(
122 "invalid replace character (%r): "
123 "need one ascii printable character" % replace)
124
125 ascii = []
126 for char in text:
127 # Remove diacriticals
128 char = normalize("NFKD", char)[0]
129
130 # Known values
131 if char in UNICODE_TO_ASCII:
132 ascii.append(UNICODE_TO_ASCII[char])
133 continue
134
135 if ord(char) <= 127:
136 # Add valid ASCII
137 ascii.append(char)
138 elif replace:
139 # non-ASCII character
140 ascii.append(replace)
141 # else: ignore it
142
143 text = ''.join(ascii)
144 return text.encode("ascii", "strict")
145
146 if __name__ == "__main__":
147 from doctest import testmod
148 from sys import exit
149 failure, total = testmod()
150 if failure:
151 print "%s failure on %s tests" % (failure, total)
152 exit(1)
153 else:
154 print "All tests are OK (count=%s)" % total
Ce script permet de créer un site complet sur un serveur (dossiers, logs, stats, base MySQL, etc...). Il nécessite une certaine structure dans la gestion des espaces web. Il nécessite aussi : a2ensite, pwgen et un fichier /root/.my.cnf pour ne pas avoir à rentrer les mot de passe MySQL de l'utilisateur root.
1 #!/bin/bash
2 ###############################################################################
3 #
4 # new_site : Permet de créer un site web sur un serveur
5 #
6 # Requiert :
7 # - a2ensite
8 # - pwgen
9 # - Fichier /root/.my.cnf bien configuré ;-)
10 #
11 # by Guillaume Kulakowski a.k.a LLaumgui <guillaume at llaumgui dot com>
12 # Version 1.0
13 #
14 ###############################################################################
15 # This program is free software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not,
27 # - write to the Free Software
28 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
29 # - See http://www.gnu.org/licenses/gpl.html
30 ###############################################################################
31
32
33 # Varibles
34 VHOST_MODEL='/etc/httpd/vhost.model.conf' # Chemin vers le modèle pour les vhost
35 VHOST_PATH='/etc/httpd/sites-available' # Chemin vers les fichiers vhost
36
37 AWSTATS_MODEL='/etc/httpd/awstats.model.conf' # Chemin vers le modèle awstats
38 AWSTATS_PATH='/etc/awstats' # Chemin vers les fichiers de conf awstats
39 AWSTATS=1 # Activer Awstats
40 MAIL_ADMIN=root # Mail de l'administrateur
41
42 # Valeurs par défaut
43 DEF_WWW_PATH="/home/llaumgui/public_html" # Chemin par défaut pour les sites
44 DEF_SERVER_ADMIN="spb-box@llaumgui.com" # Valeur par défaut pour ServerAdmin
45
46
47
48
49
50 ##
51 ## Affichage du récapitulatif
52 ##
53 function recap(){
54
55 echo "Récapitulatif"
56 echo "================================"
57 echo -e "\nConfiguration du site"
58 echo "-----------------------------"
59 echo " Adresse du site : http://$WWW_URL"
60 echo " Chemin vers le site : $WWW_PATH"
61 if [ "$PERM" != "" ]; then
62 echo " Permissions données à : $PERM"
63 fi
64
65 echo -e "\nConfiguration d'apache"
66 echo "-----------------------------"
67 echo " ServerAdmin : $SERVER_ADMIN"
68
69 echo -e "\nConfiguration de MySQL"
70 echo "-----------------------------"
71 if [ "$DB_NAME" != "" ]; then
72 echo " Base de données : $DB_NAME"
73 echo " Nom de l'utilisateur : $DB_LOGIN"
74 if [ "$1" = 0 ]; then
75 echo " Mot de passe MySQL : $DB_PASSWD"
76 else
77 echo " Mot de passe MySQL : ********"
78 fi
79 else
80 echo " *** Pas de base de données ***"
81 fi
82
83 echo -e "\nConfiguration d'Awstats"
84 echo "-----------------------------"
85 if [ $AWSTATS = 0 ]; then
86 echo " Stats Awstats : Activé"
87 else
88 echo " Stats Awstats : Désactivé"
89 fi
90 }
91
92
93
94 ##
95 ## Valider la récapitulation
96 ##
97 function recap_valid() {
98
99 echo -n "Est-ce correct ? (o/[n]) "; read CORRECT
100 if [ "$CORRECT" = "" ]; then
101 recap_valid
102 fi
103 if [ "$CORRECT" != "o" -a "$CORRECT" != "O" -a "$CORRECT" != "y" -a "$CORRECT" != "Y" ]; then
104 exit 1
105 fi
106
107 return 0
108 }
109
110
111
112
113
114 ###################################
115 ##
116 ## Définition des paramètres
117 ##
118 ###################################
119
120 ##
121 ## Défini l'url du site :
122 ##
123 function set_url() {
124
125 echo -n "URL principale du site (ex: www.google.fr) ? "; read WWW_URL
126
127 if [ "$WWW_URL" = "" ]; then
128 echo -e "\n\nErreur ! Veuillez renseigner une URL pour le site !";
129 set_url
130 fi
131
132 if [ -f "$VHOST_PATH/$WWW_URL" ]; then
133 echo -e "\n\nErreur ! Le site existe déjà !";
134 set_url
135 fi
136
137 return 0
138 }
139
140
141
142 ##
143 ## Défini le chemin vers le site
144 ## @TODO : Mettre en place la vérification du chemin.
145 function set_path() {
146
147 echo -n "Répertoire du site [$DEF_WWW_PATH/$WWW_URL] ? "; read WWW_PATH
148
149 if [ "$WWW_PATH" = "" ]; then
150 WWW_PATH="$DEF_WWW_PATH/$WWW_URL";
151 fi
152
153 if [ -d "$WWW_PATH" ]; then
154 echo -e "\n\nErreur ! Le site existe déjà !";
155 set_path
156 fi
157
158 echo -n "Donner les permissions sur $WWW_PATH/$WWW_URL/www à l'utilisateur UNIX [] ? "; read PERM
159
160 return 0
161 }
162
163
164
165 ##
166 ## Défini le paramètre ServerAdmin du vhost
167 ##
168 function set_serveradmin() {
169
170 echo -n "ServerAdmin [$DEF_SERVER_ADMIN] ? "; read SERVER_ADMIN
171
172 if [ "$SERVER_ADMIN" = "" ]; then
173 SERVER_ADMIN="$DEF_SERVER_ADMIN";
174 fi
175
176 return 0
177 }
178
179
180
181 ##
182 ## Défini le nom de la base
183 ##
184 function set_db_name() {
185
186 echo -n "Nom de la base de données [] ? "; read DB_NAME
187
188 if [ "$DB_NAME" = "" ]; then
189 return 1
190 fi
191
192 mysqlshow -u root "$DB_NAME" &> /dev/null
193 if [ $? -eq 0 ] ; then
194 echo -e "\n\nLa base de données $DB_NAME existe déjà !";
195 set_db_name
196 fi
197
198 return 0
199 }
200
201
202
203 ##
204 ## Défini du login pour la connection à la base
205 ## @TODO : Mettre en place la vérification de l'user.
206 ##
207 function set_db_login() {
208
209 echo -n "Login pour la connection à la base de données ? "; read DB_LOGIN
210
211 return 0
212 }
213
214
215
216
217 ##
218 ## Définition du mot de passe BD
219 ##function set_db_password() {
220
221 stty -echo;
222 echo -n "Mot de passe pour la base de données [] ? "; read DB_PASSWD1;
223
224 if [ "$DB_PASSWD1" = "" ]; then
225 stty echo;
226 echo -e "\n\nGénération d'un mot de passe avec pwgen..."
227 DB_PASSWD=`pwgen 16 1`
228 echo "$DB_PASSWD"
229 return 0
230 fi
231 echo -ne "\nVeuillez retaper le mot de passe [] ? "; read DB_PASSWD2;
232 if [ $DB_PASSWD1 != $DB_PASSWD2 ]; then
233 echo -e "\n\nLes 2 mots de passe saisis sont dissérents !";
234 set_db_password
235 fi
236 stty echo;
237 DB_PASSWD=$DB_PASSWD1
238
239 return 0
240 }
241
242
243
244 ##
245 ## Définition des stats
246 ##
247 function set_awstats() {
248
249 echo -n "Activer les stats Awstats ? (o/[n]) "; read TMP_AWSTATS
250 if [ "$TMP_AWSTATS" = "o" -o "$TMP_AWSTATS" = "O" -o "$TMP_AWSTATS" = "y" -o "$TMP_AWSTATS" = "Y" ]; then
251 AWSTATS=0
252 else
253 AWSTATS=1
254 fi
255
256 return 0
257 }
258
259
260
261 ##
262 ## Définition du login htaccess pour awstats
263 ##
264 function set_awstats_login() {
265
266 echo -n "Login htaccess pour Awstats ? "; read AW_LOGIN
267
268 if [ "$AW_LOGIN" = "" ]; then
269 set_awstats_login
270 fi
271
272 return 0
273 }
274
275
276
277 ##
278 ## Définition du mot de passe htaccess pour awstats
279 ##
280 function set_awstats_password() {
281
282 stty -echo;
283 echo -n "Mot de passe htaccess pour Awstats [] ? "; read AW_PASSWD1;
284
285 if [ "$AW_PASSWD1" = "" ]; then
286 stty echo;
287 echo -e "\n\nGénération d'un mot de passe avec pwgen..."
288 AW_PASSWD=`pwgen 16 1`
289 echo "$AW_PASSWD"
290 return 0
291 fi
292 echo -ne "\nVeuillez retaper le mot de passe [] ? "; read AW_PASSWD2;
293 if [ $AW_PASSWD1 != $AW_PASSWD2 ]; then
294 echo -e "\n\nLes 2 mots de passe saisis sont dissérents !";
295 set_awstats_password
296 fi
297 stty echo;
298 AW_PASSWD=$AW_PASSWD1
299
300 return 0
301 }
302
303
304
305
306
307 ###################################
308 ##
309 ## Action de création du domaine
310 ##
311 ###################################
312
313 ##
314 ## Création des répertoires web
315 ##
316 function new_www() {
317
318 mkdir "$WWW_PATH"; echo "Création du répertoire $WWW_PATH"
319 mkdir "$WWW_PATH/www"; echo "Création du répertoire $WWW_PATH/www"
320 mkdir "$WWW_PATH/logs"; echo "Création du répertoire $WWW_PATH/logs"
321 mkdir "$WWW_PATH/awstats"; echo "Création du répertoire $WWW_PATH/awstats"
322
323 if [ "$PERM" != "" ]; then
324 chown "$PERM":"$PERM" "$WWW_PATH/www"; echo "Attribution des droits sur le répertoire www"
325 fi
326
327 return 0
328 }
329
330
331
332 ##
333 ## Configuration d'apache
334 ##
335 function new_vhost() {
336
337 new_vhost=`cat $VHOST_MODEL | \
338 sed "s,@@ServerAdmin@@,$SERVER_ADMIN,g" | \
339 sed -e "s,@@DocumentRoot@@,$WWW_PATH,g" | \
340 sed "s,@@ServerName@@,$WWW_URL,g"`
341
342 if [ $AWSTATS = 0 ]; then
343 new_vhost=`echo "$new_vhost"|sed "s,#@@,,g"`
344 fi
345
346 echo "$new_vhost" > "$VHOST_PATH/$WWW_URL"; echo "Configuration du VirtualHost"
347
348 vi "$VHOST_PATH/$WWW_URL"
349 return 0
350 }
351
352
353
354 ##
355 ## Configuration d'Awstats
356 ##function new_awstats() {
357 cat $AWSTATS_MODEL | \
358 sed -e "s,@@DocumentRoot@@,$WWW_PATH,g" | \
359 sed "s,@@ServerName@@,$WWW_URL,g" \
360 > "$AWSTATS_PATH/awstats.$WWW_URL.conf"; echo "Configuration des stats"
361
362 vi "$AWSTATS_PATH/awstats.$WWW_URL.conf"
363
364 htpasswd -cb $WWW_PATH/.htpasswdstats $AW_LOGIN $AW_PASSWD
365 return 0
366 }
367
368
369
370 ##
371 ## Création de la base de données