def secure_auth(self):
     """This function Secures authentication"""
     passwd = ''.join([random.choice
                      (string.ascii_letters + string.digits)
                      for n in range(6)])
     if not self.app.pargs.user_input:
         username = input("Provide HTTP authentication user "
                          "name [{0}] :".format(SSSVariables.sss_user))
         self.app.pargs.user_input = username
         if username == "":
             self.app.pargs.user_input = SSSVariables.sss_user
     if not self.app.pargs.user_pass:
         password = getpass.getpass("Provide HTTP authentication "
                                    "password [{0}] :".format(passwd))
         self.app.pargs.user_pass = password
         if password == "":
             self.app.pargs.user_pass = passwd
     Log.debug(self, "printf username:"******"$(openssl passwd -crypt "
               "password 2> /dev/null)\n\""
               "> /etc/apache2/htpasswd-sss 2>/dev/null")
     SSSShellExec.cmd_exec(self, "printf \"{username}:"
                          "$(openssl passwd -crypt "
                          "{password} 2> /dev/null)\n\""
                          "> /etc/apache2/htpasswd-sss 2>/dev/null"
                          .format(username=self.app.pargs.user_input,
                                  password=self.app.pargs.user_pass),
                          log=False)
     SSSGit.add(self, ["/etc/apache2"],
               msg="Adding changed secure auth into Git")
Пример #2
0
    def remove(self, ppa=None, repo_url=None):
        """
        This function used to remove ppa's
        If ppa is provided adds repo file to
            /etc/apt/sources.list.d/
        command.
        """
        if ppa:
            SSSShellExec.cmd_exec(
                self, "add-apt-repository -y "
                "--remove '{ppa_name}'".format(ppa_name=ppa))
        elif repo_url:
            repo_file_path = ("/etc/apt/sources.list.d/" +
                              SSSVariables().sss_repo_file)

            try:
                repofile = open(repo_file_path, "w+")
                repofile.write(repofile.read().replace(repo_url, ""))
                repofile.close()
            except IOError as e:
                Log.debug(self, "{0}".format(e))
                Log.error(self, "File I/O error.")
            except Exception as e:
                Log.debug(self, "{0}".format(e))
                Log.error(self, "Unable to remove repo")
Пример #3
0
 def secure_auth(self):
     """This function Secures authentication"""
     passwd = ''.join([
         random.choice(string.ascii_letters + string.digits)
         for n in range(6)
     ])
     if not self.app.pargs.user_input:
         username = input("Provide HTTP authentication user "
                          "name [{0}] :".format(SSSVariables.sss_user))
         self.app.pargs.user_input = username
         if username == "":
             self.app.pargs.user_input = SSSVariables.sss_user
     if not self.app.pargs.user_pass:
         password = getpass.getpass("Provide HTTP authentication "
                                    "password [{0}] :".format(passwd))
         self.app.pargs.user_pass = password
         if password == "":
             self.app.pargs.user_pass = passwd
     Log.debug(
         self, "printf username:"******"$(openssl passwd -crypt "
         "password 2> /dev/null)\n\""
         "> /etc/apache2/htpasswd-sss 2>/dev/null")
     SSSShellExec.cmd_exec(self,
                           "printf \"{username}:"
                           "$(openssl passwd -crypt "
                           "{password} 2> /dev/null)\n\""
                           "> /etc/apache2/htpasswd-sss 2>/dev/null".format(
                               username=self.app.pargs.user_input,
                               password=self.app.pargs.user_pass),
                           log=False)
     SSSGit.add(self, ["/etc/apache2"],
                msg="Adding changed secure auth into Git")
    def remove(self, ppa=None, repo_url=None):
        """
        This function used to remove ppa's
        If ppa is provided adds repo file to
            /etc/apt/sources.list.d/
        command.
        """
        if ppa:
            SSSShellExec.cmd_exec(self, "add-apt-repository -y "
                                 "--remove '{ppa_name}'"
                                 .format(ppa_name=ppa))
        elif repo_url:
            repo_file_path = ("/etc/apt/sources.list.d/"
                              + SSSVariables().sss_repo_file)

            try:
                repofile = open(repo_file_path, "w+")
                repofile.write(repofile.read().replace(repo_url, ""))
                repofile.close()
            except IOError as e:
                Log.debug(self, "{0}".format(e))
                Log.error(self, "File I/O error.")
            except Exception as e:
                Log.debug(self, "{0}".format(e))
                Log.error(self, "Unable to remove repo")
Пример #5
0
 def add_key(self, keyids, keyserver=None):
     """
     This function adds imports repository keys from keyserver.
     default keyserver is hkp://keys.gnupg.net
     user can provide other keyserver with keyserver="hkp://xyz"
     """
     SSSShellExec.cmd_exec(
         self, "gpg --keyserver {serv}".format(
             serv=(keyserver or "hkp://keys.gnupg.net")) +
         " --recv-keys {key}".format(key=keyids))
     SSSShellExec.cmd_exec(
         self,
         "gpg -a --export --armor {0}".format(keyids) + " | apt-key add - ")
 def add_key(self, keyids, keyserver=None):
     """
     This function adds imports repository keys from keyserver.
     default keyserver is hkp://keys.gnupg.net
     user can provide other keyserver with keyserver="hkp://xyz"
     """
     SSSShellExec.cmd_exec(self, "gpg --keyserver {serv}"
                          .format(serv=(keyserver or
                                        "hkp://keys.gnupg.net"))
                          + " --recv-keys {key}".format(key=keyids))
     SSSShellExec.cmd_exec(self, "gpg -a --export --armor {0}"
                          .format(keyids)
                          + " | apt-key add - ")
    def default(self):
        """default function for info"""
        if (not self.app.pargs.apache2 and not self.app.pargs.php
           and not self.app.pargs.mysql):
            self.app.pargs.apache2 = False
            self.app.pargs.php = True
            self.app.pargs.mysql = True

        if self.app.pargs.apache2:
            if SSSAptGet.is_installed(self, 'apache2'):
                self.info_apache2()
            else:
                Log.error(self, "Apache is not installed")

        if self.app.pargs.php:
            if SSSAptGet.is_installed(self, 'php7.0-fpm'):
                self.info_php()
            else:
                Log.error(self, "PHP5 is not installed")

        if self.app.pargs.mysql:
            if SSSShellExec.cmd_exec(self, "mysqladmin ping"):
                self.info_mysql()
            else:
                Log.error(self, "MySQL is not installed")
    def default(self):
        if ((not self.app.pargs.mariadb)):
            self.app.args.print_help()
        if self.app.pargs.mariadb:
            if SSSVariables.sss_mysql_host is not "localhost":
                Log.error(
                    self, "Remote MySQL found, EasyEngine will not "
                    "install MariaDB")

            if SSSShellExec.cmd_exec(self, "mysqladmin ping") and (
                    not SSSAptGet.is_installed(self, 'mariadb-server')):

                Log.info(
                    self, "If your database size is big, "
                    "migration may take some time.")
                Log.info(
                    self, "During migration non Apache parts of "
                    "your site may remain down")
                start_migrate = input("Type \"mariadb\" to continue:")
                if start_migrate != "mariadb":
                    Log.error(self, "Not starting migration")
                self.migrate_mariadb()
            else:
                Log.error(
                    self, "Your current MySQL is not alive or "
                    "you allready installed MariaDB")
Пример #9
0
    def default(self):
        """default function for info"""
        if (not self.app.pargs.apache2 and not self.app.pargs.php
                and not self.app.pargs.mysql):
            self.app.pargs.apache2 = False
            self.app.pargs.php = True
            self.app.pargs.mysql = True

        if self.app.pargs.apache2:
            if SSSAptGet.is_installed(self, 'apache2'):
                self.info_apache2()
            else:
                Log.error(self, "Apache is not installed")

        if self.app.pargs.php:
            if SSSAptGet.is_installed(self, 'php7.0-fpm'):
                self.info_php()
            else:
                Log.error(self, "PHP5 is not installed")

        if self.app.pargs.mysql:
            if SSSShellExec.cmd_exec(self, "mysqladmin ping"):
                self.info_mysql()
            else:
                Log.error(self, "MySQL is not installed")
    def add(self):
        """Swap addition with SimpleSetupServer"""
        if SSSVariables.sss_ram < 512:
            if SSSVariables.sss_swap < 1000:
                Log.info(self, "Adding SWAP file, please wait...")

                # Install dphys-swapfile
                SSSAptGet.update(self)
                SSSAptGet.install(self, ["dphys-swapfile"])
                # Stop service
                SSSShellExec.cmd_exec(self, "service dphys-swapfile stop")
                # Remove Default swap created
                SSSShellExec.cmd_exec(self, "/sbin/dphys-swapfile uninstall")

                # Modify Swap configuration
                if os.path.isfile("/etc/dphys-swapfile"):
                    SSSFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                               "#CONF_SWAPFILE=/var/swap",
                                               "CONF_SWAPFILE=/sss-swapfile")
                    SSSFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                               "#CONF_MAXSWAP=2048",
                                               "CONF_MAXSWAP=1024")
                    SSSFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                               "#CONF_SWAPSIZE=",
                                               "CONF_SWAPSIZE=1024")
                else:
                    with open("/etc/dphys-swapfile", 'w') as conffile:
                        conffile.write("CONF_SWAPFILE=/sss-swapfile\n"
                                       "CONF_SWAPSIZE=1024\n"
                                       "CONF_MAXSWAP=1024\n")
                # Create swap file
                SSSShellExec.cmd_exec(self, "service dphys-swapfile start")
    def add(self):
        """Swap addition with SimpleSetupServer"""
        if SSSVariables.sss_ram < 512:
            if SSSVariables.sss_swap < 1000:
                Log.info(self, "Adding SWAP file, please wait...")

                # Install dphys-swapfile
                SSSAptGet.update(self)
                SSSAptGet.install(self, ["dphys-swapfile"])
                # Stop service
                SSSShellExec.cmd_exec(self, "service dphys-swapfile stop")
                # Remove Default swap created
                SSSShellExec.cmd_exec(self, "/sbin/dphys-swapfile uninstall")

                # Modify Swap configuration
                if os.path.isfile("/etc/dphys-swapfile"):
                    SSSFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                              "#CONF_SWAPFILE=/var/swap",
                                              "CONF_SWAPFILE=/sss-swapfile")
                    SSSFileUtils.searchreplace(self,  "/etc/dphys-swapfile",
                                              "#CONF_MAXSWAP=2048",
                                              "CONF_MAXSWAP=1024")
                    SSSFileUtils.searchreplace(self,  "/etc/dphys-swapfile",
                                              "#CONF_SWAPSIZE=",
                                              "CONF_SWAPSIZE=1024")
                else:
                    with open("/etc/dphys-swapfile", 'w') as conffile:
                        conffile.write("CONF_SWAPFILE=/sss-swapfile\n"
                                       "CONF_SWAPSIZE=1024\n"
                                       "CONF_MAXSWAP=1024\n")
                # Create swap file
                SSSShellExec.cmd_exec(self, "service dphys-swapfile start")
Пример #12
0
    def add(self, repo_url=None, ppa=None):
        """
        This function used to add apt repositories and or ppa's
        If repo_url is provided adds repo file to
            /etc/apt/sources.list.d/
        If ppa is provided add apt-repository using
            add-apt-repository
        command.
        """

        if repo_url is not None:
            repo_file_path = ("/etc/apt/sources.list.d/" +
                              SSSVariables().sss_repo_file)
            try:
                if not os.path.isfile(repo_file_path):
                    with open(repo_file_path, encoding='utf-8',
                              mode='a') as repofile:
                        repofile.write(repo_url)
                        repofile.write('\n')
                        repofile.close()
                elif repo_url not in open(repo_file_path,
                                          encoding='utf-8').read():
                    with open(repo_file_path, encoding='utf-8',
                              mode='a') as repofile:
                        repofile.write(repo_url)
                        repofile.write('\n')
                        repofile.close()
                return True
            except IOError as e:
                Log.debug(self, "{0}".format(e))
                Log.error(self, "File I/O error.")
            except Exception as e:
                Log.debug(self, "{0}".format(e))
                Log.error(self, "Unable to add repo")
        if ppa is not None:
            SSSShellExec.cmd_exec(
                self,
                "add-apt-repository -y '{ppa_name}'".format(ppa_name=ppa))
    def add(self, repo_url=None, ppa=None):
        """
        This function used to add apt repositories and or ppa's
        If repo_url is provided adds repo file to
            /etc/apt/sources.list.d/
        If ppa is provided add apt-repository using
            add-apt-repository
        command.
        """

        if repo_url is not None:
            repo_file_path = ("/etc/apt/sources.list.d/"
                              + SSSVariables().sss_repo_file)
            try:
                if not os.path.isfile(repo_file_path):
                    with open(repo_file_path,
                              encoding='utf-8', mode='a') as repofile:
                        repofile.write(repo_url)
                        repofile.write('\n')
                        repofile.close()
                elif repo_url not in open(repo_file_path,
                                          encoding='utf-8').read():
                    with open(repo_file_path,
                              encoding='utf-8', mode='a') as repofile:
                        repofile.write(repo_url)
                        repofile.write('\n')
                        repofile.close()
                return True
            except IOError as e:
                Log.debug(self, "{0}".format(e))
                Log.error(self, "File I/O error.")
            except Exception as e:
                Log.debug(self, "{0}".format(e))
                Log.error(self, "Unable to add repo")
        if ppa is not None:
            SSSShellExec.cmd_exec(self, "add-apt-repository -y '{ppa_name}'"
                                 .format(ppa_name=ppa))
Пример #14
0
    def default(self):
        if not self.app.pargs.mariadb:
            self.app.args.print_help()
        if self.app.pargs.mariadb:
            if SSSVariables.sss_mysql_host is not "localhost":
                Log.error(self, "Remote MySQL found, EasyEngine will not " "install MariaDB")

            if SSSShellExec.cmd_exec(self, "mysqladmin ping") and (not SSSAptGet.is_installed(self, "mariadb-server")):

                Log.info(self, "If your database size is big, " "migration may take some time.")
                Log.info(self, "During migration non Apache parts of " "your site may remain down")
                start_migrate = input('Type "mariadb" to continue:')
                if start_migrate != "mariadb":
                    Log.error(self, "Not starting migration")
                self.migrate_mariadb()
            else:
                Log.error(self, "Your current MySQL is not alive or " "you allready installed MariaDB")
def check_fqdn(self, sss_host):
    """FQDN check with Simple Setup Server, for mail server hostname must be FQDN"""
    # sss_host=os.popen("hostname -f | tr -d '\n'").read()
    if '.' in sss_host:
        SSSVariables.sss_fqdn = SSS_host
        with open('/etc/hostname', encoding='utf-8', mode='w') as hostfile:
            hostfile.write(sss_host)

        SSSShellExec.cmd_exec(
            self, "sed -i \"1i\\127.0.0.1 {0}\" /etc/hosts".format(sss_host))
        if SSSVariables.sss_platform_distro == 'debian':
            SSSShellExec.cmd_exec(self, "/etc/init.d/hostname.sh start")
        else:
            SSSShellExec.cmd_exec(self, "service hostname restart")

    else:
        sss_host = input("Enter hostname [fqdn]:")
        check_fqdn(self, sss_host)
def check_fqdn(self, sss_host):
    """FQDN check with Simple Setup Server, for mail server hostname must be FQDN"""
    # sss_host=os.popen("hostname -f | tr -d '\n'").read()
    if '.' in sss_host:
        SSSVariables.sss_fqdn = SSS_host
        with open('/etc/hostname', encoding='utf-8', mode='w') as hostfile:
            hostfile.write(sss_host)

        SSSShellExec.cmd_exec(self, "sed -i \"1i\\127.0.0.1 {0}\" /etc/hosts"
                                   .format(sss_host))
        if SSSVariables.sss_platform_distro == 'debian':
            SSSShellExec.cmd_exec(self, "/etc/init.d/hostname.sh start")
        else:
            SSSShellExec.cmd_exec(self, "service hostname restart")

    else:
        sss_host = input("Enter hostname [fqdn]:")
        check_fqdn(self, sss_host)
    def migrate_mariadb(self):
        # Backup all database
        SSSMysql.backupAll(self)

        # Add MariaDB repo
        Log.info(self, "Adding repository for MariaDB, please wait...")

        mysql_pref = ("Package: *\nPin: origin sfo1.mirrors.digitalocean.com"
                      "\nPin-Priority: 1000\n")
        with open('/etc/apt/preferences.d/'
                  'MariaDB.pref', 'w') as mysql_pref_file:
            mysql_pref_file.write(mysql_pref)

        SSSRepo.add(self, repo_url=SSSVariables.sss_mysql_repo)
        Log.debug(self,
                  'Adding key for {0}'.format(SSSVariables.sss_mysql_repo))
        SSSRepo.add_key(self,
                        '0xcbcb082a1bb943db',
                        keyserver="keyserver.ubuntu.com")

        config = configparser.ConfigParser()
        if os.path.exists('/etc/mysql/conf.d/my.cnf'):
            config.read('/etc/mysql/conf.d/my.cnf')
        else:
            config.read(os.path.expanduser("~") + '/.my.cnf')

        try:
            chars = config['client']['password']
        except Exception as e:
            Log.error(self, "Error: process exited with error %s" % e)

        Log.debug(self, "Pre-seeding MariaDB")
        Log.debug(
            self, "echo \"mariadb-server-10.0 "
            "mysql-server/root_password "
            "password \" | "
            "debconf-set-selections")
        SSSShellExec.cmd_exec(self,
                              "echo \"mariadb-server-10.0 "
                              "mysql-server/root_password "
                              "password {chars}\" | "
                              "debconf-set-selections".format(chars=chars),
                              log=False)
        Log.debug(
            self, "echo \"mariadb-server-10.0 "
            "mysql-server/root_password_again "
            "password \" | "
            "debconf-set-selections")
        SSSShellExec.cmd_exec(self,
                              "echo \"mariadb-server-10.0 "
                              "mysql-server/root_password_again "
                              "password {chars}\" | "
                              "debconf-set-selections".format(chars=chars),
                              log=False)

        # Install MariaDB
        apt_packages = SSSVariables.sss_mysql

        # If PHP is installed then install php5-mysql
        if SSSAptGet.is_installed(self, "php5-fpm"):
            apt_packages = apt_packages + ["php5-mysql"]

        # If mail server is installed then install dovecot-sql and postfix-sql
        if SSSAptGet.is_installed(self, "dovecot-core"):
            apt_packages = apt_packages + [
                "dovecot-mysql", "postfix-mysql", "libclass-dbi-mysql-perl"
            ]

        Log.info(self, "Updating apt-cache, please wait...")
        SSSAptGet.update(self)
        Log.info(self, "Installing MariaDB, please wait...")
        SSSAptGet.remove(self, ["mysql-common", "libmysqlclient18"])
        SSSAptGet.auto_remove(self)
        SSSAptGet.install(self, apt_packages)

        # Restart  dovecot and postfix if installed
        if SSSAptGet.is_installed(self, "dovecot-core"):
            SSSService.restart_service(self, 'dovecot')
            SSSService.restart_service(self, 'postfix')
Пример #18
0
    def pre_pref(self,apt_packages):
        """Pre settings to do before installation packages"""

        if set(SSSVariables.sss_mysql).issubset(set(apt_packages)):
            Log.info(self,"Adding repository for MySQL, please wait... ")
            mysql_pref = ("Package: *\nPin: origin sfo1.mirrors.digitalocean.com"
                          "\nPin-Priority: 1000\n")
            with open('/etc/apt/preferences.d/'
                      'MariaDB.pref', 'w') as mysql_pref_file:
                mysql_pref_file.write(mysql_pref)

            SSSRepo.add(self, repo_url=SSSVariables.sss_mysql_repo)
            Log.debug(self, 'Adding key for {0}'
                        .format(SSSVariables.sss_mysql_repo))
            SSSRepo.add_key(self, '0xcbcb082a1bb943db',
                               keyserver="keyserver.ubuntu.com")
            chars = ''.join(random.sample(string.ascii_letters, 8))
            Log.debug(self, "Pre-seeding MySQL")
            Log.debug(self, "echo \"mariadb-server-10.1 "
                      "mysql-server/root_password "
                      "password \" | "
                      "debconf-set-selections")

            try:
                SSSShellExec.cmd_exec(self, "echo \"mariadb-server-10.1 "
                                     "mysql-server/root_password "
                                     "password {chars}\" | "
                                     "debconf-set-selections"
                                     .format(chars=chars),
                                     log=False)
            except CommandExecutionError as e:
                Log.error("Failed to initialize MySQL package")

            Log.debug(self, "echo \"mariadb-server-10.1 "
                      "mysql-server/root_password_again "
                      "password \" | "
                      "debconf-set-selections")

            try:
                SSSShellExec.cmd_exec(self, "echo \"mariadb-server-10.1 "
                                     "mysql-server/root_password_again "
                                     "password {chars}\" | "
                                     "debconf-set-selections"
                                     .format(chars=chars),
                                     log=False)
            except CommandExecutionError as e:
                Log.error("Failed to initialize MySQL package")

            mysql_config = """
            [client]
            user = root
            password = {chars}
            """.format(chars=chars)
            config = configparser.ConfigParser()
            config.read_string(mysql_config)
            Log.debug(self, 'Writting configuration into MySQL file')
            conf_path = "/etc/mysql/conf.d/my.cnf"
            os.makedirs(os.path.dirname(conf_path), exist_ok=True)
            with open(conf_path, encoding='utf-8',
                      mode='w') as configfile:
                config.write(configfile)
            Log.debug(self, 'Setting my.cnf permission')
            SSSFileUtils.chmod(self, "/etc/mysql/conf.d/my.cnf", 0o600)

        if set(SSSVariables.sss_apache).issubset(set(apt_packages)):
            Log.info(self, "Adding repository for Apache, please wait...")
            SSSRepo.add(self, ppa=SSSVariables.sss_apache_repo)

        if set(SSSVariables.sss_php).issubset(set(apt_packages)):
            Log.info(self, "Adding repository for PHP, please wait...")
            Log.debug(self, 'Adding ppa for PHP')
            SSSRepo.add(self, ppa=SSSVariables.sss_php_repo)
Пример #19
0
    def migrate_mariadb(self):
        # Backup all database
        SSSMysql.backupAll(self)

        # Add MariaDB repo
        Log.info(self, "Adding repository for MariaDB, please wait...")

        mysql_pref = "Package: *\nPin: origin sfo1.mirrors.digitalocean.com" "\nPin-Priority: 1000\n"
        with open("/etc/apt/preferences.d/" "MariaDB.pref", "w") as mysql_pref_file:
            mysql_pref_file.write(mysql_pref)

        SSSRepo.add(self, repo_url=SSSVariables.sss_mysql_repo)
        Log.debug(self, "Adding key for {0}".format(SSSVariables.sss_mysql_repo))
        SSSRepo.add_key(self, "0xcbcb082a1bb943db", keyserver="keyserver.ubuntu.com")

        config = configparser.ConfigParser()
        if os.path.exists("/etc/mysql/conf.d/my.cnf"):
            config.read("/etc/mysql/conf.d/my.cnf")
        else:
            config.read(os.path.expanduser("~") + "/.my.cnf")

        try:
            chars = config["client"]["password"]
        except Exception as e:
            Log.error(self, "Error: process exited with error %s" % e)

        Log.debug(self, "Pre-seeding MariaDB")
        Log.debug(
            self, 'echo "mariadb-server-10.0 ' "mysql-server/root_password " 'password " | ' "debconf-set-selections"
        )
        SSSShellExec.cmd_exec(
            self,
            'echo "mariadb-server-10.0 '
            "mysql-server/root_password "
            'password {chars}" | '
            "debconf-set-selections".format(chars=chars),
            log=False,
        )
        Log.debug(
            self,
            'echo "mariadb-server-10.0 ' "mysql-server/root_password_again " 'password " | ' "debconf-set-selections",
        )
        SSSShellExec.cmd_exec(
            self,
            'echo "mariadb-server-10.0 '
            "mysql-server/root_password_again "
            'password {chars}" | '
            "debconf-set-selections".format(chars=chars),
            log=False,
        )

        # Install MariaDB
        apt_packages = SSSVariables.sss_mysql

        # If PHP is installed then install php5-mysql
        if SSSAptGet.is_installed(self, "php5-fpm"):
            apt_packages = apt_packages + ["php5-mysql"]

        # If mail server is installed then install dovecot-sql and postfix-sql
        if SSSAptGet.is_installed(self, "dovecot-core"):
            apt_packages = apt_packages + ["dovecot-mysql", "postfix-mysql", "libclass-dbi-mysql-perl"]

        Log.info(self, "Updating apt-cache, please wait...")
        SSSAptGet.update(self)
        Log.info(self, "Installing MariaDB, please wait...")
        SSSAptGet.remove(self, ["mysql-common", "libmysqlclient18"])
        SSSAptGet.auto_remove(self)
        SSSAptGet.install(self, apt_packages)

        # Restart  dovecot and postfix if installed
        if SSSAptGet.is_installed(self, "dovecot-core"):
            SSSService.restart_service(self, "dovecot")
            SSSService.restart_service(self, "postfix")
Пример #20
0
    def install(self, packages=[], apt_packages=[], disp_msg=True):
        """Start installation of packages"""
        self.msg = []
        try:
            # Default action for stack installation
            if ((not self.app.pargs.web) and (not self.app.pargs.apache2) and
                (not self.app.pargs.php) and (not self.app.pargs.mysql) and 
                (not self.app.pargs.phpmyadmin)):
                self.app.pargs.web = True
                self.app.pargs.apache2 = True
                self.app.pargs.php = True
                self.app.pargs.mysql = True

            if self.app.pargs.all:
                self.app.pargs.web = True
                self.app.pargs.apache2 = True
                self.app.pargs.php = True
                #self.app.pargs.mysql = True

            if self.app.pargs.web:
                self.app.pargs.apache2 = True
                self.app.pargs.php = True
                #self.app.pargs.mysql = True
                #self.app.pargs.wpcli = True
                #self.app.pargs.postfix = True

            if self.app.pargs.apache2:
                Log.debug(self, "Setting apt_packages variable for Apache2")
                if not SSSAptGet.is_installed(self,'apache2'):
                    apt_packages = apt_packages + SSSVariables.sss_apache

                else :
                    Log.debug(self, "Apache2 already installed")
                    Log.info(self, "Apache2 already installed")

            if self.app.pargs.php:
                Log.debug(self,"Setting apt_packages variable for PHP")
                if not SSSAptGet.is_installed(self,'php7.0-fpm'):
                    apt_packages = apt_packages + SSSVariables.sss_php
                else:
                    Log.debug(self, "PHP already installed")
                    Log.info(self, "PHP already installed")

            if self.app.pargs.mysql:
                Log.debug(self,"Setting apt_packages variable for MySQL")
                if not SSSShellExec.cmd_exec(self,"mysqladmin ping"):
                    apt_packages = apt_packages + SSSVariables.sss_mysql
                    packages = packages + [["https://raw."
                                            "githubusercontent.com"
                                            "/serversetup/tuning-primer/"
                                            "master/tuning-primer.sh",
                                            "/usr/bin/tuning-primer",
                                            "Tuning-Primer"]]
                else:
                    Log.debug(self, "MySQL connection is already alive")
                    Log.info(self, "MySQL connection is already alive")

            if self.app.pargs.phpmyadmin:
                Log.debug(self, "Setting packages varible for phpMyAdmin ")
                packages = packages + [["https://github.com/phpmyadmin/"
                                        "phpmyadmin/archive/STABLE.tar.gz",
                                        "/tmp/pma.tar.gz", "phpMyAdmin"]]


        except Exception as e:
            pass

        if len(apt_packages) or len(packages):
            Log.debug(self,"Calling pre_pref")
            self.pre_pref(apt_packages)
            if len(apt_packages):
                SSSSwap.add(self)
                Log.info(self, "Updating Apt-cache, please wait...")
                SSSAptGet.update(self)
                Log.info(self, "Installing packages, please wait...")
                SSSAptGet.install(self, apt_packages)
                SSSShellExec.cmd_exec(self, "a2enmod proxy_fcgi proxy proxy_http http2 ssl expires headers rewrite")
            if len(packages):
                Log.debug(self, "Downloading following: {0}".format(packages))
                SSSDownload.download(self, packages)
            Log.debug(self, "Calling post_pref")
            self.post_pref(apt_packages, packages)

            if disp_msg:
                if len(self.msg):
                    for msg in self.msg:
                        Log.info(self, Log.ENDC + msg)
                Log.info(self, "Successfully installed packages")
            else:
                return self.msg
Пример #21
0
    def post_pref(self, apt_packages, packages):
        """Post activity after installation of packages"""
        if len(apt_packages):
            if set(SSSVariables.sss_apache).issubset(set(apt_packages)):
                if not (os.path.isfile('/etc/apache2/conf-available/acl.conf')):
                    data = dict(webroot=SSSVariables.sss_webroot)
                    Log.debug(self, 'Writting the Apache configuration to '
                              'file /etc/apache2/conf-available/acl.conf')
                    sss_apache = open('/etc/apache2/conf-available/acl.conf',
                                    encoding='utf-8', mode='w')
                    self.app.render((data), 'acl.mustache',
                                    out=sss_apache)
                    sss_apache.close()

                    # 22222 port setting

                    Log.debug(self, 'Writting the Apache configuration to '
                              'file /etc/apache2/sites-available/'
                              '22222')

                    sss_apache = open('/etc/apache2/sites-available/22222.conf',encoding='utf-8', mode='w')
                    self.app.render((data), '22222.mustache',
                                    out=sss_apache)
                    sss_apache.close()

                    passwd = ''.join([random.choice
                                     (string.ascii_letters + string.digits)
                                     for n in range(6)])

                    try:
                        SSSShellExec.cmd_exec(self, "printf \"SSS:"
                                             "$(openssl passwd -crypt "
                                             "{password} 2> /dev/null)\n\""
                                             "> /etc/apache2/htpasswd-sss "
                                             "2>/dev/null"
                                             .format(password=passwd))
                    except CommandExecutionError as e:
                        Log.error(self, "Failed to save HTTP Auth")

                    # Create Symbolic link for 22222
                    SSSFileUtils.create_symlink(self, ['/etc/apache2/'
                                                      'sites-available/'
                                                      '22222.conf',
                                                      '/etc/apache2/'
                                                      'sites-enabled/'
                                                      '22222.conf'])

                    # Create htdocs folder
                    if not os.path.exists('{0}22222/htdocs'
                                          .format(SSSVariables.sss_webroot)):
                        Log.debug(self, "Creating directory "
                                  "{0}22222/htdocs "
                                  .format(SSSVariables.sss_webroot))
                        os.makedirs('{0}22222/htdocs'
                                    .format(SSSVariables.sss_webroot))

                    if not os.path.exists('/etc/apache2/ssl'):
                        Log.debug(self, "Creating directory "
                                  "/etc/apache2/ssl/")
                        os.makedirs('/etc/apache2/ssl')

                    try:
                        SSSShellExec.cmd_exec(self, "openssl genrsa -out "
                                             "/etc/apache2/ssl/22222.key 2048")
                        SSSShellExec.cmd_exec(self, "openssl req -new -batch  "
                                             "-subj /commonName=127.0.0.1/ "
                                             "-key /etc/apache2/ssl/22222.key "
                                             "-out /etc/apache2/ssl/"
                                             "22222.csr")

                        SSSFileUtils.mvfile(self, "/etc/apache2/ssl/22222.key",
                                           "/etc/apache2/ssl/"
                                           "22222.key.org")

                        SSSShellExec.cmd_exec(self, "openssl rsa -in "
                                             "/etc/apache2/ssl/"
                                             "22222.key.org -out "
                                             "/etc/apache2/ssl/22222.key")

                        SSSShellExec.cmd_exec(self, "openssl x509 -req -days "
                                             "3652 -in /etc/apache2/ssl/"
                                             "22222.csr -signkey "
                                             "/etc/apache2/ssl/22222.key -out "
                                             "/etc/apache2/ssl/22222.crt")

                    except CommandExecutionError as e:
                        Log.error(self, "Failed to generate SSL for 22222")

                    # Apache Configation into GIT
                    SSSGit.add(self,
                              ["/etc/apache2"], msg="Adding Apache into Git")
                    SSSService.restart_service(self, 'apache2')

                    self.msg = (self.msg + ["HTTP Auth User Name: SSS"]
                                + ["HTTP Auth Password : {0}".format(passwd)])

            if set(SSSVariables.sss_php).issubset(set(apt_packages)):
                # Create log directories
                if not os.path.exists('/var/log/php/7.0/'):
                    Log.debug(self, 'Creating directory /var/log/php/7.0/')
                    os.makedirs('/var/log/php/7.0/')

                # TOD : xdebug

                # Parse etc/php5/fpm/php.ini
                config = configparser.ConfigParser()
                Log.debug(self, "configuring php file /etc/php/7.0/fpm/php.ini")
                config.read('/etc/php/7.0/fpm/php.ini')
                config['PHP']['expose_php'] = 'Off'
                config['PHP']['post_max_size'] = '100M'
                config['PHP']['upload_max_filesize'] = '100M'
                config['PHP']['max_execution_time'] = '300'
                config['PHP']['date.timezone'] = SSSVariables.sss_timezone
                with open('/etc/php/7.0/fpm/php.ini',
                          encoding='utf-8', mode='w') as configfile:
                    Log.debug(self, "Writting php configuration into "
                              "/etc/php/7.0/fpm/php.ini")
                    config.write(configfile)

                # Prase /etc/php/7.0/fpm/php-fpm.conf
                config = configparser.ConfigParser()
                Log.debug(self, "configuring php file"
                          "/etc/php/7.0/fpm/php-fpm.conf")
                config.read_file(codecs.open("/etc/php/7.0/fpm/php-fpm.conf",
                                             "r", "utf8"))
                config['global']['error_log'] = '/var/log/php/7.0/fpm.log'
                config.remove_option('global', 'include')
                config['global']['log_level'] = 'notice'
                config['global']['include'] = '/etc/php/7.0/fpm/pool.d/*.conf'
                with codecs.open('/etc/php/7.0/fpm/php-fpm.conf',
                                 encoding='utf-8', mode='w') as configfile:
                    Log.debug(self, "writting php7 configuration into "
                              "/etc/php/7.0/fpm/php-fpm.conf")
                    config.write(configfile)

                # Parse /etc/php/7.0/fpm/pool.d/www.conf
                config = configparser.ConfigParser()
                config.read_file(codecs.open('/etc/php/7.0/fpm/pool.d/www.conf',
                                             "r", "utf8"))
                config['www']['ping.path'] = '/ping'
                config['www']['pm.status_path'] = '/status'
                config['www']['pm.max_requests'] = '500'
                config['www']['pm.max_children'] = '100'
                config['www']['pm.start_servers'] = '20'
                config['www']['pm.min_spare_servers'] = '10'
                config['www']['pm.max_spare_servers'] = '30'
                config['www']['request_terminate_timeout'] = '300'
                config['www']['pm'] = 'ondemand'
                config['www']['listen'] = '127.0.0.1:9000'
                with codecs.open('/etc/php/7.0/fpm/pool.d/www.conf',
                                 encoding='utf-8', mode='w') as configfile:
                    Log.debug(self, "writting PHP5 configuration into "
                              "/etc/php/7.0/fpm/pool.d/www.conf")
                    config.write(configfile)

                #TODO : Debug Config
                #TODO : Disable xdebug

                # PHP and Debug pull configuration
                if not os.path.exists('{0}22222/htdocs/fpm/status/'
                                      .format(SSSVariables.sss_webroot)):
                    Log.debug(self, 'Creating directory '
                              '{0}22222/htdocs/fpm/status/ '
                              .format(SSSVariables.sss_webroot))
                    os.makedirs('{0}22222/htdocs/fpm/status/'
                                .format(SSSVariables.sss_webroot))
                open('{0}22222/htdocs/fpm/status/debug'
                     .format(SSSVariables.sss_webroot),
                     encoding='utf-8', mode='a').close()
                open('{0}22222/htdocs/fpm/status/php'
                     .format(SSSVariables.sss_webroot),
                     encoding='utf-8', mode='a').close()

                # Write info.php
                if not os.path.exists('{0}22222/htdocs/php/'
                                      .format(SSSVariables.sss_webroot)):
                    Log.debug(self, 'Creating directory '
                              '{0}22222/htdocs/php/ '
                              .format(SSSVariables.sss_webroot))
                    os.makedirs('{0}22222/htdocs/php'
                                .format(SSSVariables.sss_webroot))

                with open("{0}22222/htdocs/php/info.php"
                          .format(SSSVariables.sss_webroot),
                          encoding='utf-8', mode='w') as myfile:
                    myfile.write("<?php\nphpinfo();\n?>")

                SSSFileUtils.chown(self, "{0}22222"
                                  .format(SSSVariables.sss_webroot),
                                  SSSVariables.sss_php_user,
                                  SSSVariables.sss_php_user, recursive=True)

                SSSGit.add(self, ["/etc/php/"], msg="Adding PHP into Git")
                SSSService.restart_service(self, 'php7.0-fpm')

            if set(SSSVariables.sss_mysql).issubset(set(apt_packages)):
                if not os.path.isfile("/etc/mysql/my.cnf"):
                    config = ("[mysqld]\nwait_timeout = 30\n"
                              "interactive_timeout=60\nperformance_schema = 0"
                              "\nquery_cache_type = 1")
                    config_file = open("/etc/mysql/my.cnf",
                                       encoding='utf-8', mode='w')
                    config_file.write(config)
                    config_file.close()
                else:
                    try:
                        SSSShellExec.cmd_exec(self, "sed -i \"/#max_conn"
                                             "ections/a wait_timeout = 30 \\n"
                                             "interactive_timeout = 60 \\n"
                                             "performance_schema = 0\\n"
                                             "query_cache_type = 1 \" "
                                             "/etc/mysql/my.cnf")
                    except CommandExecutionError as e:
                        Log.error(self, "Unable to update MySQL file")

                 # Set MySQL Tuning Primer permission
                SSSFileUtils.chmod(self, "/usr/bin/tuning-primer", 0o775)

                SSSGit.add(self, ["/etc/mysql"], msg="Adding MySQL into Git")
                SSSService.reload_service(self, 'mysql')

        if len(packages):
            if any('/tmp/pma.tar.gz' == x[1]
                    for x in packages):
                SSSExtract.extract(self, '/tmp/pma.tar.gz', '/tmp/')
                Log.debug(self, 'Extracting file /tmp/pma.tar.gz to '
                          'location /tmp/')
                if not os.path.exists('{0}22222/htdocs/db'
                                      .format(SSSVariables.sss_webroot)):
                    Log.debug(self, "Creating new  directory "
                              "{0}22222/htdocs/db"
                              .format(SSSVariables.sss_webroot))
                    os.makedirs('{0}22222/htdocs/db'
                                .format(SSSVariables.sss_webroot))
                shutil.move('/tmp/phpmyadmin-STABLE/',
                            '{0}22222/htdocs/db/pma/'
                            .format(SSSVariables.sss_webroot))
                shutil.copyfile('{0}22222/htdocs/db/pma/config.sample.inc.php'
                                .format(SSSVariables.sss_webroot),
                                '{0}22222/htdocs/db/pma/config.inc.php'
                                .format(SSSVariables.sss_webroot))
                Log.debug(self, 'Setting Blowfish Secret Key FOR COOKIE AUTH to  '
                          '{0}22222/htdocs/db/pma/config.inc.php file '
                          .format(SSSVariables.sss_webroot))
                blowfish_key = ''.join([random.choice
                         (string.ascii_letters + string.digits)
                         for n in range(10)])
                SSSFileUtils.searchreplace(self,
                                          '{0}22222/htdocs/db/pma/config.inc.php'
                                          .format(SSSVariables.sss_webroot),
                                          "$cfg[\'blowfish_secret\'] = \'\';","$cfg[\'blowfish_secret\'] = \'{0}\';"
                                          .format(blowfish_key))
                Log.debug(self, 'Setting HOST Server For Mysql to  '
                          '{0}22222/htdocs/db/pma/config.inc.php file '
                          .format(SSSVariables.sss_webroot))
                SSSFileUtils.searchreplace(self,
                                          '{0}22222/htdocs/db/pma/config.inc.php'
                                          .format(SSSVariables.sss_webroot),
                                          "$cfg[\'Servers\'][$i][\'host\'] = \'localhost\';","$cfg[\'Servers\'][$i][\'host\'] = \'{0}\';"
                                          .format(SSSVariables.sss_mysql_host))
                Log.debug(self, 'Setting Privileges of webroot permission to  '
                          '{0}22222/htdocs/db/pma file '
                          .format(SSSVariables.sss_webroot))
                SSSFileUtils.chown(self, '{0}22222'
                                  .format(SSSVariables.sss_webroot),
                                  SSSVariables.sss_php_user,
                                  SSSVariables.sss_php_user,
                recursive=True) 
Пример #22
0
    def post_pref(self, apt_packages, packages):
        """Post activity after installation of packages"""
        if len(apt_packages):
            if set(SSSVariables.sss_apache).issubset(set(apt_packages)):
                if not (os.path.isfile('/etc/apache2/conf-available/acl.conf')
                        ):
                    data = dict(webroot=SSSVariables.sss_webroot)
                    Log.debug(
                        self, 'Writting the Apache configuration to '
                        'file /etc/apache2/conf-available/acl.conf')
                    sss_apache = open('/etc/apache2/conf-available/acl.conf',
                                      encoding='utf-8',
                                      mode='w')
                    self.app.render((data), 'acl.mustache', out=sss_apache)
                    sss_apache.close()

                    # 22222 port setting

                    Log.debug(
                        self, 'Writting the Apache configuration to '
                        'file /etc/apache2/sites-available/'
                        '22222')

                    sss_apache = open(
                        '/etc/apache2/sites-available/22222.conf',
                        encoding='utf-8',
                        mode='w')
                    self.app.render((data), '22222.mustache', out=sss_apache)
                    sss_apache.close()

                    passwd = ''.join([
                        random.choice(string.ascii_letters + string.digits +
                                      string.punctuation) for n in range(10)
                    ])

                    try:
                        SSSShellExec.cmd_exec(
                            self, "printf \"SSS:"
                            "$(openssl passwd -crypt "
                            "{password} 2> /dev/null)\n\""
                            "> /etc/apache2/htpasswd-sss "
                            "2>/dev/null".format(password=passwd))
                    except CommandExecutionError as e:
                        Log.error(self, "Failed to save HTTP Auth")

                    # Create Symbolic link for 22222
                    SSSFileUtils.create_symlink(self, [
                        '/etc/apache2/'
                        'sites-available/'
                        '22222.conf', '/etc/apache2/'
                        'sites-enabled/'
                        '22222.conf'
                    ])

                    # Create htdocs folder
                    if not os.path.exists('{0}22222/htdocs'.format(
                            SSSVariables.sss_webroot)):
                        Log.debug(
                            self, "Creating directory "
                            "{0}22222/htdocs ".format(
                                SSSVariables.sss_webroot))
                        os.makedirs('{0}22222/htdocs'.format(
                            SSSVariables.sss_webroot))

                    if not os.path.exists('/etc/apache2/ssl'):
                        Log.debug(self, "Creating directory "
                                  "/etc/apache2/ssl/")
                        os.makedirs('/etc/apache2/ssl')

                    try:
                        SSSShellExec.cmd_exec(
                            self, "openssl genrsa -out "
                            "/etc/apache2/ssl/22222.key 2048")
                        SSSShellExec.cmd_exec(
                            self, "openssl req -new -batch  "
                            "-subj /commonName=127.0.0.1/ "
                            "-key /etc/apache2/ssl/22222.key "
                            "-out /etc/apache2/ssl/"
                            "22222.csr")

                        SSSFileUtils.mvfile(
                            self, "/etc/apache2/ssl/22222.key",
                            "/etc/apache2/ssl/"
                            "22222.key.org")

                        SSSShellExec.cmd_exec(
                            self, "openssl rsa -in "
                            "/etc/apache2/ssl/"
                            "22222.key.org -out "
                            "/etc/apache2/ssl/22222.key")

                        SSSShellExec.cmd_exec(
                            self, "openssl x509 -req -days "
                            "3652 -in /etc/apache2/ssl/"
                            "22222.csr -signkey "
                            "/etc/apache2/ssl/22222.key -out "
                            "/etc/apache2/ssl/22222.crt")

                    except CommandExecutionError as e:
                        Log.error(self, "Failed to generate SSL for 22222")

                    # Apache Configation into GIT
                    SSSGit.add(self, ["/etc/apache2"],
                               msg="Adding Apache into Git")
                    SSSService.restart_service(self, 'apache2')

                    self.msg = (self.msg + ["HTTP Auth User Name: SSS"] +
                                ["HTTP Auth Password : {0}".format(passwd)])

            #phpmyadmin config
            if set(SSSVariables.sss_pma).issubset(set(apt_packages)):
                php_conf = ("Include /etc/phpmyadmin/apache.conf")
                with open('/etc/apache2/apache2.conf', 'a') as php_conf_file:
                    php_conf_file.write(php_conf)
                """SSSFileUtils.create_symlink(self, ['/etc/phpmyadmin/apache.conf','/etc/apache2/apache2.conf'])"""
                """sss_php = open('/etc/apache2/apache2.conf',encoding='utf-8', mode='a')
                self.app.render((data), 'Include /etc/phpmyadmin/apache.conf',
                                out=sss_php)
                sss_php.close()
                """
            if set(SSSVariables.sss_php).issubset(set(apt_packages)):
                # Create log directories
                if not os.path.exists('/var/log/php/7.0/'):
                    Log.debug(self, 'Creating directory /var/log/php/7.0/')
                    os.makedirs('/var/log/php/7.0/')

                # TOD : xdebug

                # Parse etc/php5/fpm/php.ini
                config = configparser.ConfigParser()
                Log.debug(self,
                          "configuring php file /etc/php/7.0/fpm/php.ini")
                config.read('/etc/php/7.0/fpm/php.ini')
                config['PHP']['expose_php'] = 'Off'
                config['PHP']['post_max_size'] = '100M'
                config['PHP']['upload_max_filesize'] = '100M'
                config['PHP']['max_execution_time'] = '300'
                config['PHP']['date.timezone'] = SSSVariables.sss_timezone
                with open('/etc/php/7.0/fpm/php.ini',
                          encoding='utf-8',
                          mode='w') as configfile:
                    Log.debug(
                        self, "Writting php configuration into "
                        "/etc/php/7.0/fpm/php.ini")
                    config.write(configfile)

                # Prase /etc/php/7.0/fpm/php-fpm.conf
                config = configparser.ConfigParser()
                Log.debug(
                    self, "configuring php file"
                    "/etc/php/7.0/fpm/php-fpm.conf")
                config.read_file(
                    codecs.open("/etc/php/7.0/fpm/php-fpm.conf", "r", "utf8"))
                config['global']['error_log'] = '/var/log/php/7.0/fpm.log'
                config.remove_option('global', 'include')
                config['global']['log_level'] = 'notice'
                config['global']['include'] = '/etc/php/7.0/fpm/pool.d/*.conf'
                with codecs.open('/etc/php/7.0/fpm/php-fpm.conf',
                                 encoding='utf-8',
                                 mode='w') as configfile:
                    Log.debug(
                        self, "writting php7 configuration into "
                        "/etc/php/7.0/fpm/php-fpm.conf")
                    config.write(configfile)

                # Parse /etc/php/7.0/fpm/pool.d/www.conf
                config = configparser.ConfigParser()
                config.read_file(
                    codecs.open('/etc/php/7.0/fpm/pool.d/www.conf', "r",
                                "utf8"))
                config['www']['ping.path'] = '/ping'
                config['www']['pm.status_path'] = '/status'
                config['www']['pm.max_requests'] = '500'
                config['www']['pm.max_children'] = '100'
                config['www']['pm.start_servers'] = '20'
                config['www']['pm.min_spare_servers'] = '10'
                config['www']['pm.max_spare_servers'] = '30'
                config['www']['request_terminate_timeout'] = '300'
                config['www']['pm'] = 'ondemand'
                config['www']['listen'] = '127.0.0.1:9000'
                with codecs.open('/etc/php/7.0/fpm/pool.d/www.conf',
                                 encoding='utf-8',
                                 mode='w') as configfile:
                    Log.debug(
                        self, "writting PHP5 configuration into "
                        "/etc/php/7.0/fpm/pool.d/www.conf")
                    config.write(configfile)

                #TODO : Debug Config
                #TODO : Disable xdebug

                # PHP and Debug pull configuration
                if not os.path.exists('{0}22222/htdocs/fpm/status/'.format(
                        SSSVariables.sss_webroot)):
                    Log.debug(
                        self, 'Creating directory '
                        '{0}22222/htdocs/fpm/status/ '.format(
                            SSSVariables.sss_webroot))
                    os.makedirs('{0}22222/htdocs/fpm/status/'.format(
                        SSSVariables.sss_webroot))
                open('{0}22222/htdocs/fpm/status/debug'.format(
                    SSSVariables.sss_webroot),
                     encoding='utf-8',
                     mode='a').close()
                open('{0}22222/htdocs/fpm/status/php'.format(
                    SSSVariables.sss_webroot),
                     encoding='utf-8',
                     mode='a').close()

                # Write info.php
                if not os.path.exists('{0}22222/htdocs/php/'.format(
                        SSSVariables.sss_webroot)):
                    Log.debug(
                        self, 'Creating directory '
                        '{0}22222/htdocs/php/ '.format(
                            SSSVariables.sss_webroot))
                    os.makedirs('{0}22222/htdocs/php'.format(
                        SSSVariables.sss_webroot))

                with open("{0}22222/htdocs/php/info.php".format(
                        SSSVariables.sss_webroot),
                          encoding='utf-8',
                          mode='w') as myfile:
                    myfile.write("<?php\nphpinfo();\n?>")

                SSSFileUtils.chown(self,
                                   "{0}22222".format(SSSVariables.sss_webroot),
                                   SSSVariables.sss_php_user,
                                   SSSVariables.sss_php_user,
                                   recursive=True)

                SSSGit.add(self, ["/etc/php/"], msg="Adding PHP into Git")
                SSSService.restart_service(self, 'php7.0-fpm')

            if set(SSSVariables.sss_mysql).issubset(set(apt_packages)):
                if not os.path.isfile("/etc/mysql/my.cnf"):
                    config = ("[mysqld]\nwait_timeout = 30\n"
                              "interactive_timeout=60\nperformance_schema = 0"
                              "\nquery_cache_type = 1")
                    config_file = open("/etc/mysql/my.cnf",
                                       encoding='utf-8',
                                       mode='w')
                    config_file.write(config)
                    config_file.close()
                else:
                    try:
                        SSSShellExec.cmd_exec(
                            self, "sed -i \"/#max_conn"
                            "ections/a wait_timeout = 30 \\n"
                            "interactive_timeout = 60 \\n"
                            "performance_schema = 0\\n"
                            "query_cache_type = 1 \" "
                            "/etc/mysql/my.cnf")
                    except CommandExecutionError as e:
                        Log.error(self, "Unable to update MySQL file")

                # Set MySQL Tuning Primer permission
                SSSFileUtils.chmod(self, "/usr/bin/tuning-primer", 0o775)

                SSSGit.add(self, ["/etc/mysql"], msg="Adding MySQL into Git")
                SSSService.reload_service(self, 'mysql')
Пример #23
0
    def install(self, packages=[], apt_packages=[], disp_msg=True):
        """Start installation of packages"""
        self.msg = []
        try:
            # Default action for stack installation
            if ((not self.app.pargs.web) and (not self.app.pargs.apache2)
                    and (not self.app.pargs.php)
                    and (not self.app.pargs.mysql)):
                self.app.pargs.web = True
                self.app.pargs.apache2 = True
                self.app.pargs.php = True
                self.app.pargs.mysql = True
                self.app.pargs.phpmyadmin = True

            if self.app.pargs.all:
                self.app.pargs.web = True
                self.app.pargs.apache2 = True
                self.app.pargs.php = True
                self.app.pargs.mysql = True
                self.app.pargs.phpmyadmin = True

            if self.app.pargs.web:
                self.app.pargs.apache2 = True
                self.app.pargs.php = True
                self.app.pargs.mysql = True
                #self.app.pargs.wpcli = True
                #self.app.pargs.postfix = True

            if self.app.pargs.apache2:
                Log.debug(self, "Setting apt_packages variable for Apache2")
                if not SSSAptGet.is_installed(self, 'apache2'):
                    apt_packages = apt_packages + SSSVariables.sss_apache

                else:
                    Log.debug(self, "Apache2 already installed")
                    Log.info(self, "Apache2 already installed")

            if self.app.pargs.php:
                Log.debug(self, "Setting apt_packages variable for PHP")
                if not SSSAptGet.is_installed(self, 'php7.0-fpm'):
                    apt_packages = apt_packages + SSSVariables.sss_php
                else:
                    Log.debug(self, "PHP already installed")
                    Log.info(self, "PHP already installed")

            if self.app.pargs.phpmyadmin:
                Log.debug(self, "Setting apt_packages variable for PhpMyadmin")
                if not SSSAptGet.is_installed(self, 'phpmyadmin'):
                    apt_packages = apt_packages + SSSVariables.sss_pma
                else:
                    Log.debug(self, "PhpMyadmin already installed")
                    Log.info(self, "PhpMyadmin already installed")

            if self.app.pargs.mysql:
                Log.debug(self, "Setting apt_packages variable for MySQL")
                if not SSSShellExec.cmd_exec(self, "mysqladmin ping"):
                    apt_packages = apt_packages + SSSVariables.sss_mysql
                    packages = packages + [[
                        "https://raw."
                        "githubusercontent.com"
                        "/serversetup/tuning-primer/"
                        "master/tuning-primer.sh", "/usr/bin/tuning-primer",
                        "Tuning-Primer"
                    ]]
                else:
                    Log.debug(self, "MySQL connection is already alive")
                    Log.info(self, "MySQL connection is already alive")

        except Exception as e:
            pass

        if len(apt_packages) or len(packages):
            Log.debug(self, "Calling pre_pref")
            self.pre_pref(apt_packages)
            if len(apt_packages):
                SSSSwap.add(self)
                Log.info(self, "Updating Apt-cache, please wait...")
                SSSAptGet.update(self)
                Log.info(self, "Installing packages, please wait...")
                SSSAptGet.install(self, apt_packages)
                SSSShellExec.cmd_exec(
                    self,
                    "a2enmod proxy_fcgi proxy proxy_http http2 ssl expires headers rewrite"
                )
            if len(packages):
                Log.debug(self, "Downloading following: {0}".format(packages))
                SSSDownload.download(self, packages)
            Log.debug(self, "Calling post_pref")
            self.post_pref(apt_packages, packages)

            if disp_msg:
                if len(self.msg):
                    for msg in self.msg:
                        Log.info(self, Log.ENDC + msg)
                Log.info(self, "Successfully installed packages")
            else:
                return self.msg
Пример #24
0
    def pre_pref(self, apt_packages):
        """Pre settings to do before installation packages"""

        if set(SSSVariables.sss_pma).issubset(set(apt_packages)):
            Log.info(self, "Adding repository for phpMyAdmin ,please wait...")
            """pma_pref = ("def origin http://ppa.launchpad.net/nijel/phpmyadmin/ubuntu trusty main")

            with open('/etc/apt/sources.list.d/', 'w') as pma_pref_file:
                pma_pref_file.write(pma_pref)"""
            SSSRepo.add(self, repo_url=SSSVariables.sss_pma_repo_url)

            Log.debug(self,
                      'Adding key for {0}'.format(SSSVariables.sss_pma_repo))
            SSSRepo.add_key(self, '06ED541C', keyserver="keyserver.ubuntu.com")
            chars = ''.join(random.sample(string.ascii_letters, 8))

            Log.debug(self, "Adding ppa for phpMyAdmin")
            SSSRepo.add(self, ppa=SSSVariables.sss_pma_repo)

        if set(SSSVariables.sss_mysql).issubset(set(apt_packages)):
            Log.info(self, "Adding repository for MySQL, please wait... ")
            mysql_pref = (
                "Package: *\nPin: origin sfo1.mirrors.digitalocean.com"
                "\nPin-Priority: 1000\n")
            with open('/etc/apt/preferences.d/'
                      'MariaDB.pref', 'w') as mysql_pref_file:
                mysql_pref_file.write(mysql_pref)

            SSSRepo.add(self, repo_url=SSSVariables.sss_mysql_repo)
            Log.debug(self,
                      'Adding key for {0}'.format(SSSVariables.sss_mysql_repo))
            SSSRepo.add_key(self,
                            '0xcbcb082a1bb943db',
                            keyserver="keyserver.ubuntu.com")
            chars = ''.join(random.sample(string.ascii_letters, 8))
            Log.debug(self, "Pre-seeding MySQL")
            Log.debug(
                self, "echo \"mariadb-server-10.1 "
                "mysql-server/root_password "
                "password \" | "
                "debconf-set-selections")

            try:
                SSSShellExec.cmd_exec(
                    self,
                    "echo \"mariadb-server-10.1 "
                    "mysql-server/root_password "
                    "password {chars}\" | "
                    "debconf-set-selections".format(chars=chars),
                    log=False)
            except CommandExecutionError as e:
                Log.error("Failed to initialize MySQL package")

            Log.debug(
                self, "echo \"mariadb-server-10.1 "
                "mysql-server/root_password_again "
                "password \" | "
                "debconf-set-selections")

            try:
                SSSShellExec.cmd_exec(
                    self,
                    "echo \"mariadb-server-10.1 "
                    "mysql-server/root_password_again "
                    "password {chars}\" | "
                    "debconf-set-selections".format(chars=chars),
                    log=False)
            except CommandExecutionError as e:
                Log.error("Failed to initialize MySQL package")

            mysql_config = """
            [client]
            user = root
            password = {chars}
            """.format(chars=chars)
            config = configparser.ConfigParser()
            config.read_string(mysql_config)
            Log.debug(self, 'Writting configuration into MySQL file')
            conf_path = "/etc/mysql/conf.d/my.cnf"
            os.makedirs(os.path.dirname(conf_path), exist_ok=True)
            with open(conf_path, encoding='utf-8', mode='w') as configfile:
                config.write(configfile)
            Log.debug(self, 'Setting my.cnf permission')
            SSSFileUtils.chmod(self, "/etc/mysql/conf.d/my.cnf", 0o600)

        if set(SSSVariables.sss_apache).issubset(set(apt_packages)):
            Log.info(self, "Adding repository for Apache, please wait...")
            SSSRepo.add(self, ppa=SSSVariables.sss_apache_repo)

        if set(SSSVariables.sss_php).issubset(set(apt_packages)):
            Log.info(self, "Adding repository for PHP, please wait...")
            Log.debug(self, 'Adding ppa for PHP')
            SSSRepo.add(self, ppa=SSSVariables.sss_php_repo)