Предполагается, что Apache HTTP настроен по статье CentOS: установка Apache HTTP + suEXEC + mod_fcgid.
Добавлять сайты приходится не часто – но каждый раз это целая история.
Было решено сделать скрипт, что бы автоматизировать этот процесс. Пока он только создаёт пользователя, директории и файлы.
ToDo – добавить создание базы и создание конфигурационных файлов virtualhost-а
для Apache HTTP и NGINX.
Скрипт разбит на две части: “createvhost.py
” – основной, управляющий, скрипт и “createvhostFuncts.py
” – с описанием функций.UPD: это первая, достаточно убогая попытка. Полная версия скрипта – в посте Python: утилита для создания нового Apache VirtualHost + пользователь + база MySQL.
Python:
# python -V Python 2.6.6
Первый скрипт:
#!/usr/bin/env python import createvhostFuncts as fun import os import crypt import getpass fun.isroot() username = raw_input('Please, enter username: ') password = getpass.getpass('Please, enter user password: ') domain = raw_input("Please, enter domain: ") vdir = '/var/www/' logdir = '/var/log/httpd/' print ('nYou entered:nn' + username + ' as username;n' + domain + ' as domain name.n') try: if fun.answer('Is it correct data? ('y' or 'n', Ctrl+C for exit) '): print 'OK, proceeding.' else: exit('Exit now.') except (KeyboardInterrupt, EOFError): exit('Exiting.n') print 'nAdding new user %s...' % username if fun.uadd(username, password): print 'Done.n' else: exit('Error! Exit now.n') print 'Creating new directory %s%s/%s/%s...' % (vdir,'vhosts',username,domain) if fun.mkdir(vdir, 'vhosts/', username + '/', domain + '/'): print 'Done.n' else: exit('Error! Exit now.n') print 'Creating new directory %s%s/%s/%s...' % (vdir,'php-cgi',username,domain) if fun.mkdir(vdir, 'php-cgi/', username + '/', domain + '/'): print 'Done.n' else: exit('Error! Exit now.n') print 'Copying php.cgi file...' if fun.cpcgi(vdir + 'php-cgi/php.cgi', (vdir + 'php-cgi/' + username + '/' + domain)): print 'Done.n' else: exit('Error! Exit now.n') print 'Chmoding ' + vdir + 'php-cgi/' + username + '/' + domain + '/php.cgi' + '...' if fun.chmcgi(vdir + 'php-cgi/' + username + '/' + domain + '/php.cgi', 0755): print 'Done.n' else: exit('Error! Exit now.n') print 'Chowning directory ' + vdir + 'php-cgi/' + username + '/' + domain + '...' if fun.chowdir(vdir + 'php-cgi/' + username, username): print 'Done.n' else: exit('Error! Exit now.n') print 'Chowning directory ' + vdir + 'vhosts/' + username + '/' + domain + '...' if fun.chowdir(vdir + 'vhosts/' + username, username): print 'Done.n' else: exit('Error! Exit now.n') print 'Creating log-file ' + logdir + domain + '-access.log...' if fun.tchlog(logdir, domain, '-access.log'): print 'Done.n' else: exit('Error! Exit now.n') print 'Creating log-file ' + logdir + domain + '-error.log...' if fun.tchlog(logdir, domain, '-error.log'): print 'Done.n' else: exit('Error! Exit now.n')
И функции:
#!/usr/bin/env python import sys, os, crypt, subprocess, errno, errno, shutil, pwd, grp def exit(exit_message): print exit_message sys.exit(1) def isroot(): if os.geteuid() != 0: exit('nMust be started as root.n') def answer(prompt, choice='Yes or no, please!'): while True: result = raw_input(prompt) if result in ('y', 'Y', 'yes', 'Yes'): return True elif result in ('n', 'N', 'no', 'No'): return False else: print(choice) # add user, set password def uadd(user, pwd): # create salt salt = os.urandom(6).encode('base_64') # encrypt password encpass = crypt.crypt(pwd, salt) if subprocess.call("useradd -p" + encpass + ' ' + user, shell=True) == 0: return True # create directories def mkdir(path, type, user, domain): dir = path + type + user + domain try: if not os.path.isdir(dir): os.makedirs(dir) return True except OSError as e: print 'Something going wrong: %s' % e # copy php.cgi script def cpcgi(src, dst): try: shutil.copy(src, dst) if os.path.isfile(dst + '/php.cgi'): return True except: print 'Something going wrong!' # chmod php.cgi file def chmcgi(src, perm): try: os.chmod(src, perm) return True except: print 'Something going wrong!' # chown user's php-cgi and site directory def chowdir(path, user): uid = pwd.getpwnam(user).pw_uid gid = grp.getgrnam(user).gr_gid try: for root, dirs, files in os.walk(path): for a in dirs: os.chown(os.path.join(root, a), uid, gid) for a in files: os.chown(os.path.join(root, a), uid, gid) os.chown(path, uid, gid) return True except: print 'Something going wrong!' # create lof-files def tchlog(path, domain, type): logfile = path + domain + type try: open(logfile, 'a') return True except: print 'Something going wrong!'
“И со всем этим на борту мы теперь попробуем взлететь” (с)
Пример работы:
$ ./createvhost.py Must be started as root.
# ./createvhost.py Please, enter username: user Please, enter user password: Please, enter domain: domain.org.ua You entered: user as username; domain.org.ua as domain name. Is it correct data? ('y' or 'n', Ctrl+C for exit) y OK, proceeding. Adding new user user... Done. Creating new directory /var/www/vhosts/user/domain.org.ua... Done. Creating new directory /var/www/php-cgi/user/domain.org.ua... Done. Copying php.cgi file... Done. Chmoding /var/www/php-cgi/user/domain.org.ua/php.cgi... Done. Chowning directory /var/www/php-cgi/user/domain.org.ua... Done. Chowning directory /var/www/vhosts/user/domain.org.ua... Done. Creating log-file /var/log/httpd/domain.org.ua-access.log... Done. Creating log-file /var/log/httpd/domain.org.ua-error.log... Done.