Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 25 Aug 2006 10:42:32 -0700
From:      Scott Oertel <freebsd@scottevil.com>
To:        questions@freebsd.org
Subject:   Re: A webhosting script?
Message-ID:  <44EF3688.3060109@scottevil.com>
In-Reply-To: <44EF35CB.6080301@scottevil.com>
References:  <7.0.1.0.2.20060825140411.02343870@broadpark.no>	<3ee9ca710608250830x46b52a1es74486b37a8f7254c@mail.gmail.com>	<7.0.1.0.2.20060825174443.0239c1c0@broadpark.no>	<1678437486.20060825161049@yournetplus.com> <44EF35CB.6080301@scottevil.com>

next in thread | previous in thread | raw e-mail | index | archive | help
For some reason the script doesn't really show up, ill just paste it here:

#!/usr/local/bin/python
#
# Site managment tool
# Written by: Scott Oertel
#


# imports
import os, sys, re, pwd
from crypt import crypt
import time, commands

global httpd_conf
httpd_conf = '/usr/local/etc/apache22/vhosts.conf'

class AddSite:
    def __init__(self, username, password, domain):
    self.username = username
    self.password = password
    self.domain = domain
    def run(self):
    self.AddUser()
    self.AddVhost()
    apacheStatus = 
commands.getstatusoutput('/usr/local/etc/rc.d/apache22.sh reload')
    if apacheStatus[0] != 0:
        print "Apache reload failed!"
        print apacheStatus[1]
        sys.exit()
   
    def losuj_salt (self, lenght = 8):
    '''Generate random salt from letters and digits. '''
    import random
    # pool for random bytes
    # pool = range (48, 127)
    pool = []
    for x in range (48, 127):
        pool.append (chr (x))
    s = [ '$1$' ] # start of salt indicating md5 encryption
    i = 0
    # check whether salt is between 0 and 8 (including both)
    if lenght < 0:
        lenght = 0
    if lenght > 8:
        lenght = 8
    # Generate up to 8 random, printable characters
    while i < lenght:
        s.append (s[i] + random.choice ( pool ))
        i += 1
    return s[lenght] + '$'
   
   
    def AddVhost(self):
    vhostDirective = '''
   
    ### vhost for #domain# ###
   
    <VirtualHost *:80>
        ServerAdmin support@#domain#
        DocumentRoot #domainDir#
        ServerName #domain#
        ServerAlias www.#domain#
        ErrorLog /var/log/apache/#domain#-error_log
        CustomLog /var/log/apache/#domain#-access_log common
        SuexecUserGroup #user# #user#
    </VirtualHost>
   
    ### end vhost for #domain# ###
   
    '''
    confObj = open(httpd_conf, 'a')
    os.mkdir(self.homeDir + "/html", 0775)
    os.chown(self.homeDir + "/html", pwd.getpwnam(self.username)[2], 
pwd.getpwnam(self.username)[3])
    vhostDirective = re.sub("#domain#", self.domain, vhostDirective)
    vhostDirective = re.sub("#domainDir#", self.homeDir + "html", 
vhostDirective)
    vhostDirective = re.sub("#user#", self.username, vhostDirective)
    vhostObj = open(httpd_conf, 'a')
    vhostObj.write(vhostDirective)
   
    def AddUser(self):
      #check if site exists
      vhost_fileObj = open(httpd_conf, 'r')
      vhost_file = vhost_fileObj.read()
      try:
    pwd.getpwnam(self.username)
    sys.stderr.write("That username is already in use!\n")
    sys.exit()
      except KeyError:
    pass
      if re.search(r'[#]{3}[\s]+vhost\sfor\s(%s)[\s][#]{3}' % 
self.domain, vhost_file) != None:
    sys.stderr.write("That domain already has a vhost entry.\n")
    sys.exit()
      else:
    ## add the user/vhost ##
    # generate home directory
    name, tld = self.domain.split('.')
    self.homeDir = "/home/" + tld + "/" + name + "/"
    hash = crypt(self.password, self.losuj_salt())
    tmpfile = open("/root/tmp/jsiIKw23", "w")
    tmpfile.write(hash)
    tmpfile.close()
    # add the user
    groupStatus = commands.getstatusoutput("pw groupadd %s" % self.username)
    pwStatus = commands.getstatusoutput("pw user add -n %s -G %s -d %s 
-s /bin/date -m -H 0 < /root/tmp/jsiIKw23" % (self.username, 
self.username, self.homeDir))
    if groupStatus[0] != 0 or pwStatus[0] != 0:
        print "User creation failed."
        print groupStatus
        print pwStatus
        sys.exit()
    # remove the temp file
    #os.remove("/tmp/jsiIKw23")
    # permissions setup
    try:
        os.chown(self.homeDir, pwd.getpwnam(self.username)[2], 
pwd.getpwnam(self.username)[3])
    except KeyError:
        print "Setting folder permissions failed, trying again..",
        time.sleep(3)
        os.chown(self.homeDir, pwd.getpwnam(self.username)[2], 
pwd.getpwnam(self.username)[3])
        print "Success!"
   

class DeleteSite:
    def __init__(self, username, domain):
    self.username = username
    self.domain = domain
    def run(self):
    rmuserStatus = commands.getstatusoutput("/usr/sbin/rmuser -y %s" % 
self.username)
    if rmuserStatus[0] != 0:
        print "Ran into trouble deleting the username!"
        print rmuserStatus[1]
        sys.exit(2)
    else:
        self.deleteVhost()
        apacheStatus = 
commands.getstatusoutput('/usr/local/etc/rc.d/apache22.sh reload')
        if apacheStatus[0] != 0:
        print "Apache reload failed!"
        print apacheStatus[1]
        sys.exit()
   
    def deleteVhost(self):
    vhostFile = open(httpd_conf, "r")
    vhostFileData = vhostFile.read()
    vhostFileData = re.sub(r'[#]{3}[\s]+vhost\sfor\s(' + self.domain + 
')[\s][#]{3}[\n\t\n\t<>@A-Za-z\*\s0-9:\./\-_]+[#]{3}\send\svhost\sfor\s(' 
+ self.domain + ')\s[#]{3}[\n\t]+'
                   , '', vhostFileData)
    vhostFile.close()
    vhostFile = open(httpd_conf, "w")
    vhostFile.write(vhostFileData)
    vhostFile.close()
       
def usage():
    print '''Site Management Tool v1.0

Usage:

./site.py -a --user=<username> --pass=<password> --domain=<domain>
./site.py -d --user=<username> --domain=<domain>
./site.py -s --domain=<domain>

-s     to suspend a site. (Not implemented)
-d     deletes a site permanently.
-a     adds a site and user to the system.

'''

   
if __name__ == "__main__":
    import getopt
    try:
    opts, args = getopt.getopt(sys.argv[1:], ":adss:", [ "user=", 
"pass=", "domain=", "help" ])
    except getopt.GetoptError: # bad arguments - print usage and exit
    usage()
    sys.exit(2)
   
    for opt in opts:
    if opt[0] == "-a":
        try:
        if opts[1][0] == "--user" and opts[2][0] == "--pass" and 
opts[3][0] == "--domain":
            newEntry = AddSite(opts[1][1], opts[2][1], opts[3][1])
            newEntry.run()
            print "Added %s." % opts[3][1]
        else:
            usage()
            sys.exit(2)   
        except IndexError:
        usage()
        sys.exit(2)
       
    elif opt[0] == "-d":
        try:
        if opts[1][0] == "--user" and opts[2][0] == "--domain":
            delEntry = DeleteSite(opts[1][1], opts[2][1])
            delEntry.run()
            print "Deleted %s!" % opts[2][1]
        else:
            usage()
            sys.exit(2)
        except IndexError:
        usage()
        sys.exit(2)
       
    elif opt[0] == "-s":
        print "Try back later."
       
    elif opt[0] == "--help":
        usage()
        sys.exit(2)



   
   
   
   

Scott Oertel wrote:
> I wrote a simple one that could use improvement a while back for a 
> FreeBSD box I had, you could use it as a reference point. It's 
> developed in python though.
>
> -Scott
>
> Duane Hill wrote:
>> On Friday, August 25, 2006 at 3:45:08 PM, Kyrre confabulated:
>>
>>  
>>> At 17:30 25.08.2006, Andy Greenwood wrote:
>>>    
>>>> We use perl scripts here. Unfortunately, I can't provide any 
>>>> specific examples.
>>>>       
>>
>>  
>>> So stop trolling :)
>>>     
>>
>>  
>>> Perl is obsolete anyway, thanks though.
>>>     
>>
>> So, if Perl is obsolete, what does a guy use for a replacement?
>>
>>   
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> freebsd-questions@freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-questions
> To unsubscribe, send any mail to "freebsd-questions-unsubscribe@freebsd.org"




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?44EF3688.3060109>