1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
|
#!/usr/bin/python
from datetime import date,datetime
import os, errno, sqlite3, sys, getopt, shutil
registry_paths=["/etc/domainctl/registry"]
registry = "domains.db"
database = "domains.db"
def main(argv):
try:
opts, args = getopt.getopt(argv, "acd:Dhlvz", ["add", "create", "delete=", "dir", "help", "list", "vhost", "zone"])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-a", "--add"):
if len(args) < 3:
usage()
sys.exit(2)
user, subdomain, domain, email = split_args(args)
add_domain(user, subdomain, domain, email)
elif opt in ("-c", "--create"):
create_db()
elif opt in ("-d", "--delete"):
if len(args) < 1:
usage()
sys.exit(2)
if arg in ("u", "user"):
delete_user(args[0])
elif arg in ("d", "domain"):
if args[0].count(".") < 2:
delete_domain(args[0])
else:
subdomain, domain = args[0].split(".", 1)
delete_subdomain(subdomain, domain)
else:
usage()
sys.exit(2)
elif opt in ("-D", "--dir"):
if len(args) < 1:
usage()
sys.exit(2)
if args[0].count(".") < 2:
subdomain, domain = ("", args[0])
else:
subdomain, domain = args[0].split(".", 1)
build_structure(subdomain, domain)
elif opt in ("-h", "--help"):
usage()
sys.exit(2)
elif opt in ("-l", "--list"):
list_domains()
elif opt in ("-v", "--vhost"):
if len(args) < 1:
usage()
sys.exit(2)
if args[0].count(".") < 2:
subdomain = ''
domain = args[0]
else:
subdomain, domain = args[0].split(".", 1)
build_vhost(subdomain, domain)
elif opt in ("-z", "--zone"):
if len(args) < 1:
usage()
sys.exit(2)
build_zone(args[0])
else:
usage()
sys.exit(2)
sys.exit(0)
def split_args(args):
user = args[0]
if args[1].count(".") < 2:
subdomain, domain = ("", args[1])
else:
subdomain, domain = args[1].split(".", 1)
email = args[2]
return user, subdomain, domain, email
def add_domain(user, subdomain, domain, email):
try:
db = sqlite3.connect(database)
db.execute("""
insert into store (user, subdomain, domain, email)
values (?, ?, ?, ?)
""", (user.lower(), subdomain.lower(), domain.lower(), email.lower(),))
db.commit()
except sqlite3.OperationalError as e:
print "error: %s" % e
sys.exit(1)
def create_db():
"""Creates the database for tracking control info."""
try:
db = sqlite3.connect(database)
db.execute("""
create table store (
id integer primary key,
user text not null,
subdomain text not null,
domain text not null,
email text not null
)
""")
except sqlite3.OperationalError as e:
print "error: %s" % e
sys.exit(1)
def delete_user(user):
"""Drops a user entry, and all associated domains, from the database."""
try:
db = sqlite3.connect(database)
resultset = db.execute("""
select 1 from store
where user = ?
""", (user,)).fetchall()
if len(resultset) == 0:
print "User '%s' does not exist." % user
sys.exit(1)
resultset = db.execute("""
select subdomain, domain from store
where user = ?
""", (user,)).fetchall()
print "WARNING! You are about to delete the user '%s' and the following domains:"
for subdomain, domain in resultset:
if subdomain != '':
domain = subdomain + "." + domain
print domain
answer = raw_input("Are you sure that you want to do this? (y/N): ")
if answer.lower() == "y" or answer.lower() == "yes":
db.execute("""
delete from store
where user = ?
""", (user,))
db.commit()
else:
print "Aborted."
except sqlite3.OperationalError as e:
print "error: %s" % e
sys.exit(1)
def delete_domain(domain):
"""Drops a domain (or subdomain), and all associated subdomains, from the database."""
if domain.count(".") < 2:
subdomain, domain = ("", args[1])
else:
subdomain, domain = domain.split(".", 1)
try:
db = sqlite3.connect(database)
resultset = db.execute("""
select 1 from store
where domain = ?
""", (domain,)).fetchall()
if len(resultset) == 0:
print "Domain '%s' does not exist." % domain
sys.exit(1)
resultset = db.execute("""
select subdomain, domain from store
where domain = ?
and subdomain != ''
""", (domain,)).fetchall()
print "WARNING! You are about to delete the domain '%s' and the following subdomains:" % domain
for subdomain, domain in resultset:
print "%s.%s" % (subdomain, domain)
answer = raw_input("Are you sure that you want to do this? (y/N): ")
if answer.lower() == "y" or answer.lower() == "yes":
db.execute("""
delete from store
where domain = ?
""", (domain,))
else:
print "Aborted."
except sqlite3.OperationalError as e:
print "error: %s" % e
sys.exit(1)
def delete_subdomain(subdomain, domain):
"""Drops a subdomain from the database."""
try:
db = sqlite3.connect(database)
resultset = db.execute("""
select 1 from store
where domain = ?
and subdomain = ?
""", (domain, subdomain,)).fetchall()
if len(resultset) == 0:
print "Subdomain '%s.%s' does not exist." % (subdomain, domain)
sys.exit(1)
print "WARNING! You are about to delete the subdomain '%s.%s'." % (subdomain, domain)
answer = raw_input("Are you sure that you want to do this? (y/N): ")
if answer.lower() == "y" or answer.lower() == "yes":
db.execute("""
delete from store
where domain = ?
and subdomain = ?
""", (domain, subdomain,))
else:
print "Aborted."
except sqlite3.OperationalError as e:
print "error: %s" % e
sys.exit(1)
def list_domains():
"""Prints the stored domains in a visually helpful manner."""
try:
db = sqlite3.connect(database)
resultset = db.execute("""
select * from store
""").fetchall()
for id, user, subdomain, domain, email in resultset:
if subdomain != "":
domain = subdomain + "." + domain
print "%s%s%s" % (user.ljust(16), email.ljust(32), domain)
except sqlite3.OperationalError as e:
print "error: %s" % e
sys.exit(1)
def is_registered(user, domain, subdomain):
db = sqlite3.connect(registry)
try:
resultset = db.execute("""select 1 from domains
where user = ?
and domain = ?
and subdomain = ?
""").fetchall()
except sqlite3.OperationalError as e:
create_db()
exit(1)
for result in resultset:
print result
line = registry.readline()
while line:
line = line.rstrip("\n")
if line.startswith("%s:%s" % (user, domain)) == True:
registry.close()
return "domain"
elif line == "%s:%s:%s" % (user, domain, subdomain):
registry.close()
return "subdomain"
line = registry.readline()
registry.close()
return None
def register(user, domain, subdomain):
registry = open("registry", "a")
registry.write("%s:%s:%s\n" % (user, domain, subdomain))
registry.close()
def build_zone(domain):
zone_file = "%s.zone" % domain
try:
db = sqlite3.connect(database)
resultset = db.execute("""
select user from store
where domain = ?
and subdomain = ''
""", (domain,)).fetchall()
user = resultset[0][0]
resultset = db.execute("""
select subdomain from store
where domain = ?
and subdomain != ''
""", (domain,)).fetchall()
except sqlite3.OperationalError as e:
print "error: %s" % e
sys.exit(1)
if os.path.isfile(zone_file):
shutil.copy(zone_file, zone_file + ".old")
template = open("zone_template.txt", "r")
zone = open(zone_file, "w")
line = template.readline()
while line:
line = line.replace("[user]", user)
line = line.replace("[domain]", domain)
line = line.replace("[serial]", date.strftime(datetime.today(), format="%Y%m%d%M"))
zone.write(line)
line = template.readline()
zone.seek(0, os.SEEK_END)
for subdomain in resultset:
zone.write("%sIN CNAME %s.\n" % (subdomain[0].ljust(32), domain))
zone.close()
template.close()
def add_sub_to_zone(domain, subdomain):
zone_file = "%s.zone" % domain
zone = open(zone_file, "a")
zone.seek(0, os.SEEK_END)
zone.write("%s\tIN\tCNAME\t%s.\n" % (subdomain, domain))
zone.close()
def build_vhost(subdomain, domain):
if subdomain:
vhost_file = "%s.%s" % (subdomain, domain)
else:
vhost_file = domain
try:
db = sqlite3.connect(database)
resultset = db.execute("""
select user from store
where domain = ?
and subdomain = ?
limit 1
""", (domain, subdomain,)).fetchall()
user = resultset[0][0]
except sqlite3.OperationalError as e:
print "error: %s" % e
sys.exit(1)
if os.path.isfile(vhost_file):
shutil.copy(vhost_file, vhost_file + ".old")
template = open("vhost_template.txt", "r")
vhost = open(vhost_file, "w")
line = template.readline()
while line:
if not subdomain:
line = line.replace("[subdomain].[domain]", domain)
line = line.replace("[ServerAlias]", "ServerAlias www.%s" % domain)
else:
line = line.replace("[ServerAlias]", "")
line = line.replace("[user]", user)
line = line.replace("[domain]", domain)
line = line.replace("[subdomain]", subdomain)
line = line.replace("//", "/")
vhost.write(line)
line = template.readline()
vhost.close()
template.close()
def build_structure(subdomain, domain):
try:
db = sqlite3.connect(database)
resultset = db.execute("""
select user from store
where domain = ?
and subdomain = ?
limit 1
""", (domain, subdomain,)).fetchall()
if len(resultset) == 0:
if subdomain:
print "Subdomain '%s.%s' does not exist." % (subdomain, domain)
else:
print "Domain '%s' does not exist." % domain
sys.exit(1)
user = resultset[0][0]
if not subdomain:
os.makedirs(name="/var/www/%s/%s/public_html" % (user, domain), mode=0755)
os.makedirs(name="/var/www/%s/%s/cgi-bin" % (user, domain), mode=0755)
else:
os.makedirs(name="/var/www/%s/%s/%s/public_html" % (user, domain, subdomain), mode=0755)
os.makedirs(name="/var/www/%s/%s/%s/cgi-bin" % (user, domain, subdomain), mode=0755)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
else:
raise
except sqlite3.OperationalError as e:
print "error: %s" % e
sys.exit(1)
def usage():
print "domainctl <option>"
print " -a, --add <user> <domain> <email> Add a domain to the database."
print " -d, --delete user <user> Delete a user from the database."
print " domain <domain> Delete a domain from the database."
print " -D, --dir <domain> Generate the dir structure for a given domain."
print " -c, --create Create the domains database."
print " -h, --help Show usage information."
print " -l, --list List domains in the database."
print " -v, --vhost <domain> Generate the vhost file for a given domain."
print " -z, --zone <domain> Generate the zonefile for a given domain."
if __name__ == "__main__":
main(sys.argv[1:])
|