post
poster: toraton
description: domainctl - update 2
language: Python
[download]
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
#!/usr/bin/python

import os
import errno
import sys
import shutil
import sqlite3
import optparse

from datetime import date,datetime

database = "domains.db"

homedir = "/var/www"

def main(argv):
    """domainctl is a tool for managing domains, subdomains, users, and email addresses."""

    parser = optparse.OptionParser()

    parser.add_option("-a", "--add", nargs=4, dest="add_domain",
                      help="add a DOMAIN", metavar="DOMAIN USER EMAIL IP")
    parser.add_option("-c", "--create", dest="create_database",
                      help="create the database", action="store_true")
    parser.add_option("-d", "--delete-domain", nargs=1, dest="delete_domain",
                      help="delete a DOMAIN", metavar="DOMAIN")
    parser.add_option("-D", "--delete-user", nargs=1, dest="delete_user",
                      help="delete a USER", metavar="USER")
    parser.add_option("-e", "--domain-email", nargs=2, dest="domain_email",
                      help="set EMAIL for DOMAIN", metavar="DOMAIN EMAIL")
    parser.add_option("-E", "--user-email", nargs=2, dest="user_email",
                      help="set EMAIL for USER", metavar="USER EMAIL")
    parser.add_option("-g", "--generate", nargs=1, dest="generate",
                      help="generate zonefiles, vhost, and dirs for DOMAIN",
                      metavar="DOMAIN")
    parser.add_option("-G", "--generate-all", dest="generate_all",
                      help="generate all files for all domains",
                      action="store_true")
    parser.add_option("-i", "--domain-ip", nargs=2, dest="ip",
                      help="set IP for DOMAIN", metavar="DOMAIN IP")
    parser.add_option("-l", "--list", dest="list",
                      help="list domains and users", action="store_true")
    parser.add_option("-s", "--dirs", nargs=1, dest="build_dirs",
                      help="build dir structure for DOMAIN", metavar="DOMAIN")
    parser.add_option("-u", "--domain-user", nargs=2, dest="domain_user",
                      help="set USER for DOMAIN", metavar="DOMAIN USER")
    parser.add_option("-v", "--vhost", nargs=1, dest="build_vhost",
                      help="build vhost for DOMAIN", metavar="DOMAIN")
    parser.add_option("-z", "--zone", nargs=1, dest="build_zone",
                      help="build zonefile for DOMAIN", metavar="DOMAIN")
    
    options, args = parser.parse_args()
    
    if not sys.argv[1:]:
        parser.print_help()
    elif options.add_domain:
        subdomain, domain = split_args(options.add_domain[0]) 
        user = options.add_domain[1]
        email = options.add_domain[2]
        ip = options.add_domain[3]
        add_domain(subdomain, domain, user, email, ip)
    elif options.create_database:
        create_db()
    elif options.delete_domain:
        subdomain, domain = split_args(options.delete_domain)
        if subdomain:
            delete_subdomain(subdomain, domain)
        else:
            delete_domain(domain)
    elif options.delete_user:
        delete_user(options.delete_user)
    elif options.domain_email:
        subdomain, domain = split_args(options.domain_email[0])
        email = options.domain_email[1]
        set_domain_email(subdomain, domain, email)
    elif options.user_email:
        user = options.user_email[0]
        email = options.domain_email[1]
        set_user_email(user, email)
    elif options.generate:
        subdomain, domain = split_args(options.generate)
        build_vhost(subdomain, domain)
        build_zone(subdomain, domain)
        build_structure(subdomain, domain)
    elif options.generate_all:
        generate_all()
    elif options.ip:
        subdomain, domain = split_args(options.ip[0])
        ip = options.ip[1]
        set_domain_ip(subdomain, domain, ip)
    elif options.list:
        list_domains()
    elif options.build_dirs:
        subdomain, domain = split_args(options.build_dirs) 
        build_structure(subdomain, domain)
    elif options.domain_user:
        subdomain, domain = split_args(options.domain_user[0])
        user = options.domain_user[1]
        set_domain_user(subdomain, domain, user)
    elif options.build_vhost:
        subdomain, domain = split_args(options.build_vhost)
        build_vhost(subdomain, domain)
    elif options.build_zone:
        subdomain, domain = split_args(options.build_zone)
        build_zone(subdomain, domain)
        
    sys.exit(0)
        
def split_args(args):
    """Splits the subdomain from a domain and returns both."""

    if args.count(".") < 2:
        subdomain, domain = ("", args)
    else:
        subdomain, domain = args.split(".", 1)

    return subdomain, domain

def add_domain(subdomain, domain, user, email, ip):
    """Adds a domain (or subdomain) to the db."""

    try:
        db = sqlite3.connect(database)

        resultset = db.execute("""
            select 1 from store
                where domain = ?
                  and subdomain = ''
        """, (domain,)).fetchall()

        if subdomain and not resultset:
            print ("Cannot create subdomain '%s.%s' without matching domain." 
                % (subdomain,domain))
            sys.exit(1)

        resultset = db.execute("""
            select 1 from store
                where domain = ?
                  and subdomain = ?
        """, (domain, subdomain,)).fetchall()

        if resultset:
            if subdomain:
                print "Subdomain '%s.%s' already exists." % (subdomain,
                                                             domain)
            else:
                print "Domain '%s' already exists." % (domain)

        
        db.execute("""
            insert into store (user, subdomain, domain, email, ip)
                values (?, ?, ?, ?, ?)
        """, (user.lower(), subdomain.lower(), domain.lower(), email.lower(), ip.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,
                ip        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 subdomain, domain from store
                where user = ?
        """, (user,)).fetchall()

        if len(resultset) == 0:
            print "User '%s' does not exist." % (user)
            sys.exit(1)

        print "WARNING! You are about to delete the user '%s' and" % (user)
        print "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.
    """

    try:
        db = sqlite3.connect(database)

        resultset = db.execute("""
            select 1 from store
                where domain = ?
        """, (domain,)).fetchall()

        if not resultset:
            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" % (domain)
        print "the following subdomains:"
        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,))
            db.commit()
        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 generate_all():
    """Generate all files for all domains."""

    try:
        db = sqlite3.connect(database)

        resultset = db.execute("""
            select domain, subdomain from store
        """).fetchall()
    except OperationalError as e:
        print "error: %s" % (e)
        sys.exit(1)

    for domain, subdomain in resultset:
        build_structure(subdomain, domain)
        build_vhost(subdomain, domain)
        build_zone(subdomain, domain)

def list_domains():
    """Prints the stored domains in a visually helpful manner."""

    try:
        db = sqlite3.connect(database)

        resultset = db.execute("""
            select user, subdomain, domain, ip, email from store
        """).fetchall()

        print "%s%s%s%s" % ("user".ljust(16), "email".ljust(32), "domain".ljust(32), "ip")
        for user, subdomain, domain, ip, email in resultset:
            if subdomain != "":
                domain = subdomain + "." + domain
            print "%s%s%s%s" % (user.ljust(16), email.ljust(32), domain.ljust(32), ip)

    except sqlite3.OperationalError as e:
        print "error: %s" % e
        sys.exit(1)

def build_zone(subdomain, domain):
    """Builds the zonefile from a template."""

    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, ip from store
                where domain = ?
        """, (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, ip in resultset:
        if ip == "cname" and subdomain:
            zone.write("%sIN    CNAME    %s.\n" % (subdomain.ljust(32), domain))
        elif subdomain:
            zone.write("%sIN    A        %s\n" % (subdomain.ljust(32), ip))
        elif not subdomain:
            zone.write("%sIN    A        %s\n" % ("@".ljust(32), ip))

    zone.close()
    template.close()

def set_domain_user(subdomain, domain, user):
    """Set the user associated with a given domain."""

    try:
        db = sqlite3.connect(database)

        resultset = db.execute("""
            select 1 from store
                where domain = ?
                  and subdomain = ?
        """, (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)

        resultset = db.execute("""
            update store
                set user = ?
                where domain = ?
                  and subdomain = ?
        """, (email, domain, subdomain,))

        db.commit()
    except sqlite2.OperationalError as e:
        print "error: %s" % e
        sys.exit(1)


def build_vhost(subdomain, domain):
    """Build the apache vhost file from a template."""

    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):
    """Build the dir structure for hosting the domain or subdomain."""

    try:
        db = sqlite3.connect(database)
        
        resultset = db.execute("""
            select user from store
                where domain = ?
                  and subdomain = ?
                limit 1
        """, (domain, subdomain,)).fetchall()

        if not resultset:
            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="%s/%s/%s/public_html" % (homedir, user, domain), mode=0755)
            os.makedirs(name="%s/%s/%s/cgi-bin" % (homedir, user, domain), mode=0755)
        else: 
            os.makedirs(name="%s/%s/%s/%s/public_html" % (homedir, user, domain, subdomain), mode=0755)
            os.makedirs(name="%s/%s/%s/%s/cgi-bin" % (homedir, 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 set_domain_email(subdomain, domain, email):
    """Set the email associated with a given domain."""

    try:
        db = sqlite3.connect(database)
    
        resultset = db.execute("""
            select 1 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)

        resultset = db.execute("""
            update store
                set email = ?
                where domain = ?
                  and subdomain = ?
        """, (email, domain, subdomain,))

        db.commit()
    except sqlite2.OperationalError as e:
        print "error: %s" % e
        sys.exit(1)

def set_user_email(user, email):
    """Set the email associated with a given user."""

    try:
        db = sqlite3.connect(database)

        resultset = db.execute("""
            select subdomain, domain from store
                where user = ?
        """, (user,)).fetchall()

        if len(resultset) == 0:
            print "User '%s' does not exist." % (user)

        print "WARNING! You are about to change the email address for user '%s'."
        print "This will affect 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("""
                update store
                    set email = ?
                    where user = ?
            """, (email, user,))
            db.commit()
        else:
            print "Aborted."

    except sqlite3.OperationalError as e:
        print "error: %s" % e
        sys.exit(1)    

def usage():
    """Print usage info."""

    print "domainctl <option>"
    print "    -a, --add <domain> <user> <email> <ip>      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 "    -c, --create                                Create the domains database."
    print "    -D, --dir <domain>                          Generate the dir structure for a given domain."
    print "    -e, --domainemail <domain> <email>          Set the email address for a given domain."
    print "    -E, --useremail <user> <email>              Set the email address for a given user." 
    print "    -g, --generate <domain>                     Generate zonfile, vhost, and dir structure."
    print "    -h, --help                                  Show usage information."
    print "    -i, --ip <domain> [<ip>|cname]              Set the IP (or CNAME) for a given domain."
    print "    -l, --list                                  List domains in the database."
    print "    -u, --user <domain> <user>                  Set the user associated with a given domain."
    print "    -v, --vhost <domain>                        Generate the vhost file for a given domain."
    print "    -z, --zone <domain>                         Generate the zonefile for a given domain."
    sys.exit(2)

def set_domain_ip(subdomain, domain, ip):
    """Set the IP for a domain or optionally set a CNAME."""

    try:
        db = sqlite3.connect(database)

        resultset = db.execute("""
            select 1 from store
                where domain = ?
                  and subdomain = ?
        """, (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)

        db.execute("""
            update store
                set ip = ?
                where domain = ?
                  and subdomain = ?
        """, (ip, domain, subdomain,))
        db.commit()

    except sqlite3.OperationalError as e:
        print "error: %s" % e
        sys.exit(1)

if __name__ == "__main__":
    main(sys.argv[1:])