Exemple #1
0
 def clean_redis(self):
     """This function clears Redis cache"""
     if (WOAptGet.is_installed(self, "redis-server")):
         Log.info(self, "Cleaning Redis cache")
         WOShellExec.cmd_exec(self, "redis-cli flushall")
     else:
         Log.info(self, "Redis is not installed")
Exemple #2
0
 def clean_fastcgi(self):
     if (os.path.isdir("/var/run/nginx-cache")
             and os.path.exists('/usr/sbin/nginx')):
         Log.info(self, "Cleaning NGINX FastCGI cache")
         WOShellExec.cmd_exec(self, "rm -rf /var/run/nginx-cache/*")
         WOService.restart_service(self, 'nginx')
     else:
         Log.error(self, "Unable to clean FastCGI cache", False)
Exemple #3
0
 def wpcli(self, command):
     """WP-CLI wrapper"""
     try:
         WOShellExec.cmd_exec(
             self, '{0} --allow-root '.format(WOVar.wo_wpcli_path) +
             '{0}'.format(command))
     except Exception:
         Log.error(self, "WP-CLI command failed")
Exemple #4
0
 def download_key(self, key_url):
     """
     This function download gpg keys and add import them with apt-key add"
     """
     try:
         WOShellExec.cmd_exec(
             self, "curl -sL {0} ".format(key_url) + "| apt-key add -")
     except Exception as e:
         Log.debug(self, "{0}".format(e))
         Log.error(self, "Unable to import repo keys")
Exemple #5
0
 def add_key(self, keyids, keyserver=None):
     """
     This function adds imports repository keys from keyserver.
     default keyserver is hkp://keyserver.ubuntu.com
     user can provide other keyserver with keyserver="hkp://xyz"
     """
     WOShellExec.cmd_exec(
         self, "apt-key adv --keyserver {serv}".format(
             serv=(keyserver or "hkp://keyserver.ubuntu.com")) +
         " --recv-keys {key}".format(key=keyids))
Exemple #6
0
 def renew(self, domain):
     """Renew letsencrypt certificate with acme.sh"""
     try:
         WOShellExec.cmd_exec(
             self, "{0} ".format(WOAcme.wo_acme_exec) +
             "--renew -d {0} --ecc --force".format(domain))
     except CommandExecutionError as e:
         Log.debug(self, str(e))
         Log.error(self, 'Unable to renew certificate')
     return True
Exemple #7
0
 def remove_cron(self,cmd):
     if WOShellExec.cmd_exec(self, "crontab -l | grep -q \'{0}\'".format(cmd)):
         if not WOShellExec.cmd_exec(self, "/bin/bash -c "
                                                 "\"crontab "
                                                 "-l | sed '/{0}/d'"
                                                 "| crontab -\""
                                                 .format(cmd)):
             Log.error(self, "Failed to remove crontab entry",False)
     else:
         Log.debug(self, "Cron not found")
Exemple #8
0
    def setcron_weekly(self,cmd,comment='Cron set by WordOps',user='******',min=0,hour=12):
        if not WOShellExec.cmd_exec(self, "crontab -l | grep -q \'{0}\'".format(cmd)):

            WOShellExec.cmd_exec(self, "/bin/bash -c \"crontab -l "
                                             "2> /dev/null | {{ cat; echo -e"
                                             " \\\""
                                             "\\n0 0 * * 0 "
                                             "{0}".format(cmd) +
                                             " # {0}".format(comment)+
                                             "\\\"; } | crontab -\"")
            Log.debug(self, "Cron set")
Exemple #9
0
    def import_slow_log(self):
        """Default function for import slow log"""
        if os.path.isdir("{0}22222/htdocs/db/anemometer".format(
                WOVariables.wo_webroot)):
            if os.path.isfile("/var/log/mysql/mysql-slow.log"):
                # Get Anemometer user name and password
                Log.info(self, "Importing MySQL slow log to Anemometer")
                host = os.popen("grep -e \"\'host\'\" {0}22222/htdocs/".format(
                    WOVariables.wo_webroot) +
                                "db/anemometer/conf/config.inc.php  "
                                "| head -1 | cut -d\\\' -f4 | "
                                "tr -d '\n'").read()
                user = os.popen("grep -e \"\'user\'\" {0}22222/htdocs/".format(
                    WOVariables.wo_webroot) +
                                "db/anemometer/conf/config.inc.php  "
                                "| head -1 | cut -d\\\' -f4 | "
                                "tr -d '\n'").read()
                password = os.popen("grep -e \"\'password\'\" {0}22222/".
                                    format(WOVariables.wo_webroot) +
                                    "htdocs/db/anemometer/conf"
                                    "/config.inc.php "
                                    "| head -1 | cut -d\\\' -f4 | "
                                    "tr -d '\n'").read()

                # Import slow log Anemometer using pt-query-digest
                try:
                    WOShellExec.cmd_exec(
                        self, "pt-query-digest --user={0} "
                        "--password={1} "
                        "--review D=slow_query_log,"
                        "t=global_query_review "
                        "--history D=slow_query_log,t="
                        "global_query_review_history "
                        "--no-report --limit=0% "
                        "--filter=\" \\$event->{{Bytes}} = "
                        "length(\\$event->{{arg}}) "
                        "and \\$event->{{hostname}}=\\\""
                        "{2}\\\"\" "
                        "/var/log/mysql/mysql-slow.log".format(
                            user, password, host))
                except CommandExecutionError as e:
                    Log.debug(self, str(e))
                    Log.error(self, "MySQL slow log import failed.")
            else:
                Log.error(
                    self, "MySQL slow log file not found,"
                    " so not imported slow logs")
        else:
            Log.error(
                self, "Anemometer is not installed." + Log.ENDC +
                "\n Install Anemometer with:" + Log.BOLD +
                "\n `wo stack install --utils`" + Log.ENDC)
Exemple #10
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"
     """
     WOShellExec.cmd_exec(
         self, "gpg --keyserver {serv}".format(
             serv=(keyserver or "hkp://keys.gnupg.net")) +
         " --recv-keys {key}".format(key=keyids))
     WOShellExec.cmd_exec(
         self,
         "gpg -a --export --armor {0}".format(keyids) + " | apt-key add - ")
Exemple #11
0
    def debug_fpm(self):
        """Start/Stop PHP5-FPM debug"""
        # PHP5-FPM start global debug
        if (self.app.pargs.fpm == 'on' and not self.app.pargs.site_name):
            if not WOShellExec.cmd_exec(
                    self, "grep \"log_level = debug\" "
                    "/etc/{0}/"
                    "fpm/php-fpm.conf".format("php/7.2")):
                Log.info(self, "Setting up PHP5-FPM log_level = debug")
                config = configparser.ConfigParser()
                config.read('/etc/{0}/fpm/php-fpm.conf'.format("php/7.2"))
                config.remove_option('global', 'include')
                config['global']['log_level'] = 'debug'
                config['global'][
                    'include'] = '/etc/{0}/fpm/pool.d/*.conf'.format("php/7.2")
                with open('/etc/{0}/fpm/php-fpm.conf'.format("php/7.2"),
                          encoding='utf-8',
                          mode='w') as configfile:
                    Log.debug(
                        self, "Writting php5-FPM configuration into "
                        "/etc/{0}/fpm/php-fpm.conf".format("php/7.2"))
                    config.write(configfile)
                self.trigger_php = True
            else:
                Log.info(self, "PHP5-FPM log_level = debug already setup")

            self.msg = self.msg + ['/var/log/{0}/fpm.log'.format("php/7.2")]

        # PHP5-FPM stop global debug
        elif (self.app.pargs.fpm == 'off' and not self.app.pargs.site_name):
            if WOShellExec.cmd_exec(
                    self, "grep \"log_level = debug\" "
                    "/etc/{0}/fpm/php-fpm.conf".format("php/7.2")):
                Log.info(self, "Disabling PHP5-FPM log_level = debug")
                config = configparser.ConfigParser()
                config.read('/etc/{0}/fpm/php-fpm.conf'.format("php/7.2"))
                config.remove_option('global', 'include')
                config['global']['log_level'] = 'notice'
                config['global'][
                    'include'] = '/etc/{0}/fpm/pool.d/*.conf'.format("php/7.2")
                with open('/etc/{0}/fpm/php-fpm.conf'.format("php/7.2"),
                          encoding='utf-8',
                          mode='w') as configfile:
                    Log.debug(
                        self, "writting php5 configuration into "
                        "/etc/{0}/fpm/php-fpm.conf".format("php/7.2"))
                    config.write(configfile)

                self.trigger_php = True
            else:
                Log.info(self, "PHP5-FPM log_level = debug  already disabled")
Exemple #12
0
 def siteurlhttps(self, domain):
     wo_site_webroot = ('/var/www/{0}'.format(domain))
     WOFileUtils.chdir(self, '{0}/htdocs/'.format(wo_site_webroot))
     if WOShellExec.cmd_exec(
             self, "{0} --allow-root core is-installed".format(
                 WOVar.wo_wpcli_path)):
         wo_siteurl = (WOShellExec.cmd_exec_stdout(
             self, "{0} option get siteurl ".format(WOVar.wo_wpcli_path) +
             "--allow-root --quiet"))
         test_url = re.split(":", wo_siteurl)
         if not (test_url[0] == 'https'):
             Log.wait(self, "Updating site url with https")
             try:
                 WOShellExec.cmd_exec(
                     self, "{0} option update siteurl "
                     "\'https://{1}\' --allow-root".format(
                         WOVar.wo_wpcli_path, domain))
                 WOShellExec.cmd_exec(
                     self, "{0} option update home "
                     "\'https://{1}\' --allow-root".format(
                         WOVar.wo_wpcli_path, domain))
                 WOShellExec.cmd_exec(
                     self, "{0} search-replace \'http://{1}\'"
                     "\'https://{1}\' --skip-columns=guid "
                     "--skip-tables=wp_users".format(
                         WOVar.wo_wpcli_path, domain))
             except Exception as e:
                 Log.debug(self, str(e))
                 Log.failed(self, "Updating site url with https")
             else:
                 Log.valide(self, "Updating site url with https")
Exemple #13
0
 def add_key(self, keyid, keyserver=None):
     """
     This function adds imports repository keys from keyserver.
     default keyserver is hkp://keyserver.ubuntu.com
     user can provide other keyserver with keyserver="hkp://xyz"
     """
     try:
         WOShellExec.cmd_exec(
             self, "apt-key adv --keyserver {serv}".format(
                 serv=(keyserver or "hkp://keyserver.ubuntu.com")) +
             " --recv-keys {key}".format(key=keyid))
     except Exception as e:
         Log.debug(self, "{0}".format(e))
         Log.error(self, "Unable to import repo key")
Exemple #14
0
    def upgrade_php56(self):
        if WOVariables.wo_platform_distro == "ubuntu":
            if os.path.isfile("/etc/apt/sources.list.d/ondrej-php5-5_6-{0}."
                              "list".format(WOVariables.wo_platform_codename)):
                Log.error(self, "Unable to find PHP 5.5")
        else:
            if not(os.path.isfile(WOVariables.wo_repo_file_path) and
                   WOFileUtils.grep(self, WOVariables.wo_repo_file_path,
                                    "php55")):
                Log.error(self, "Unable to find PHP 5.5")

        Log.info(self, "During PHP update process non nginx-cached"
                 " parts of your site may remain down.")

        # Check prompt
        if (not self.app.pargs.no_prompt):
            start_upgrade = input("Do you want to continue:[y/N]")
            if start_upgrade != "Y" and start_upgrade != "y":
                Log.error(self, "Not starting PHP package update")

        if WOVariables.wo_platform_distro == "ubuntu":
            WORepo.remove(self, ppa="ppa:ondrej/php5")
            WORepo.add(self, ppa=WOVariables.wo_php_repo)
        else:
            WOAptGet.remove(self, ["php5-xdebug"])
            WOFileUtils.searchreplace(self, WOVariables.wo_repo_file_path,
                                      "php55", "php56")

        Log.info(self, "Updating apt-cache, please wait...")
        WOAptGet.update(self)
        Log.info(self, "Installing packages, please wait ...")
        if (WOVariables.wo_platform_codename == 'trusty' or WOVariables.wo_platform_codename == 'xenial' or WOVariables.wo_platform_codename == 'bionic'):
            WOAptGet.install(self, WOVariables.wo_php5_6 + WOVariables.wo_php_extra)
        else:
            WOAptGet.install(self, WOVariables.wo_php)

        if WOVariables.wo_platform_distro == "debian":
            WOShellExec.cmd_exec(self, "pecl install xdebug")

            with open("/etc/php5/mods-available/xdebug.ini",
                      encoding='utf-8', mode='a') as myfile:
                myfile.write(";zend_extension=/usr/lib/php5/20131226/"
                             "xdebug.so\n")

            WOFileUtils.create_symlink(self, ["/etc/php5/mods-available/"
                                       "xdebug.ini", "/etc/php5/fpm/conf.d"
                                                     "/20-xedbug.ini"])

        Log.info(self, "Successfully upgraded from PHP 5.5 to PHP 5.6")
    def default(self):
        if ((not self.app.pargs.mariadb)):
            self.app.args.print_help()
        if self.app.pargs.mariadb:
            if WOVariables.wo_mysql_host is not "localhost":
                Log.error(
                    self, "Remote MySQL server in use, skipping local install")

            if WOShellExec.cmd_exec(self, "mysqladmin ping") and (
                    not WOAptGet.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 nginx-cached 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")
Exemple #16
0
    def default(self):
        """default function for info"""
        if (not self.app.pargs.nginx and not self.app.pargs.php
                and not self.app.pargs.mysql and not self.app.pargs.php73):
            self.app.pargs.nginx = True
            self.app.pargs.php = True
            self.app.pargs.mysql = True
            if WOAptGet.is_installed(self, 'php7.3-fpm'):
                self.app.pargs.php73 = True

        if self.app.pargs.nginx:
            if (WOAptGet.is_installed(self, 'nginx-custom')
                    or WOAptGet.is_installed(self, 'nginx-common')):
                self.info_nginx()
            else:
                Log.error(self, "Nginx is not installed")

        if self.app.pargs.php:
            if WOAptGet.is_installed(self, 'php7.2-fpm'):
                self.info_php()
            else:
                Log.error(self, "PHP 7.2 is not installed")

        if self.app.pargs.php73:
            if WOAptGet.is_installed(self, 'php7.3-fpm'):
                self.info_php73()
            else:
                Log.error(self, "PHP 7.3 is not installed")

        if self.app.pargs.mysql:
            if WOShellExec.cmd_exec(self, "mysqladmin ping"):
                self.info_mysql()
            else:
                Log.error(self, "MySQL is not installed")
Exemple #17
0
    def default(self):
        pargs = self.app.pargs
        if ((not pargs.mariadb)):
            self.app.args.print_help()
        if pargs.mariadb:
            if WOVar.wo_distro == 'raspbian':
                Log.error(self, "MariaDB upgrade is not available on Raspbian")
            if WOVar.wo_mysql_host != "localhost":
                Log.error(
                    self, "Remote MySQL server in use, skipping local install")

            if (WOShellExec.cmd_exec(self, "mysqladmin ping")):

                Log.info(
                    self, "If your database size is big, "
                    "migration may take some time.")
                Log.info(
                    self, "During migration non nginx-cached parts of "
                    "your site may remain down")
                if not pargs.force:
                    start_upgrade = input("Do you want to continue:[y/N]")
                    if start_upgrade != "Y" and start_upgrade != "y":
                        Log.error(self, "Not starting package update")
                if not pargs.ci:
                    self.migrate_mariadb()
                else:
                    self.migrate_mariadb(ci=True)
            else:
                Log.error(
                    self, "Your current MySQL is not alive or "
                    "you allready installed MariaDB")
Exemple #18
0
    def deploycert(self, wo_domain_name):
        """Deploy Let's Encrypt certificates with acme.sh"""
        if not os.path.isfile('/etc/letsencrypt/renewal/{0}_ecc/fullchain.cer'.
                              format(wo_domain_name)):
            Log.error(self, 'Certificate not found. Deployment canceled')

        Log.debug(self,
                  "Cert deployment for domain: {0}".format(wo_domain_name))

        try:
            Log.wait(self, "Deploying SSL cert")
            if WOShellExec.cmd_exec(
                    self,
                    "mkdir -p {0}/{1} && {2} --install-cert -d {1} --ecc "
                    "--cert-file {0}/{1}/cert.pem --key-file {0}/{1}/key.pem "
                    "--fullchain-file {0}/{1}/fullchain.pem "
                    "--ca-file {0}/{1}/ca.pem --reloadcmd \"nginx -t && "
                    "service nginx restart\" ".format(WOVar.wo_ssl_live,
                                                      wo_domain_name,
                                                      WOAcme.wo_acme_exec)):
                Log.valide(self, "Deploying SSL cert")
            else:
                Log.failed(self, "Deploying SSL cert")
                Log.error(self, "Unable to deploy certificate")

            if os.path.isdir('/var/www/{0}/conf/nginx'.format(wo_domain_name)):

                sslconf = open(
                    "/var/www/{0}/conf/nginx/ssl.conf".format(wo_domain_name),
                    encoding='utf-8',
                    mode='w')
                sslconf.write("listen 443 ssl http2;\n"
                              "listen [::]:443 ssl http2;\n"
                              "ssl_certificate     {0}/{1}/fullchain.pem;\n"
                              "ssl_certificate_key     {0}/{1}/key.pem;\n"
                              "ssl_trusted_certificate {0}/{1}/ca.pem;\n"
                              "ssl_stapling_verify on;\n".format(
                                  WOVar.wo_ssl_live, wo_domain_name))
                sslconf.close()

            if not WOFileUtils.grep(self, '/var/www/22222/conf/nginx/ssl.conf',
                                    '/etc/letsencrypt'):
                Log.info(self, "Securing WordOps backend with current cert")
                sslconf = open("/var/www/22222/conf/nginx/ssl.conf",
                               encoding='utf-8',
                               mode='w')
                sslconf.write("ssl_certificate     {0}/{1}/fullchain.pem;\n"
                              "ssl_certificate_key     {0}/{1}/key.pem;\n"
                              "ssl_trusted_certificate {0}/{1}/ca.pem;\n"
                              "ssl_stapling_verify on;\n".format(
                                  WOVar.wo_ssl_live, wo_domain_name))
                sslconf.close()

            WOGit.add(self, ["/etc/letsencrypt"],
                      msg="Adding letsencrypt folder")

        except IOError as e:
            Log.debug(self, str(e))
            Log.debug(self, "Error occured while generating " "ssl.conf")
        return 0
Exemple #19
0
 def export_cert(self):
     """Export acme.sh csv certificate list"""
     if not WOShellExec.cmd_exec(
             self, "{0} ".format(WOAcme.wo_acme_exec) +
             "--list --listraw > /var/lib/wo/cert.csv"):
         Log.error(self, "Unable to export certs list")
     WOFileUtils.chmod(self, '/var/lib/wo/cert.csv', 0o600)
Exemple #20
0
    def default(self):
        """default function for info"""
        pargs = self.app.pargs
        if (not pargs.nginx and not pargs.php and not pargs.mysql
                and not pargs.php73 and not pargs.php74 and not pargs.php80
                and not pargs.php81):
            pargs.nginx = True
            pargs.php = True
            pargs.mysql = True
            if WOAptGet.is_installed(self, 'php7.3-fpm'):
                pargs.php73 = True
            if WOAptGet.is_installed(self, 'php7.4-fpm'):
                pargs.php74 = True
            if WOAptGet.is_installed(self, 'php8.0-fpm'):
                pargs.php80 = True
            if WOAptGet.is_installed(self, 'php8.1-fpm'):
                pargs.php81 = True

        if pargs.nginx:
            if ((not WOAptGet.is_installed(self, 'nginx-custom'))
                    and (not os.path.exists('/usr/bin/nginx'))):
                Log.info(self, "Nginx is not installed")
            else:
                self.info_nginx()

        if pargs.php:
            if WOAptGet.is_installed(self, 'php7.2-fpm'):
                self.info_php()
            else:
                Log.info(self, "PHP 7.2 is not installed")

        if pargs.php73:
            if WOAptGet.is_installed(self, 'php7.3-fpm'):
                self.info_php73()
            else:
                Log.info(self, "PHP 7.3 is not installed")

        if pargs.php74:
            if WOAptGet.is_installed(self, 'php7.4-fpm'):
                self.info_php74()
            else:
                Log.info(self, "PHP 7.4 is not installed")

        if pargs.php80:
            if WOAptGet.is_installed(self, 'php8.0-fpm'):
                self.info_php80()
            else:
                Log.info(self, "PHP 8.0 is not installed")

        if pargs.php81:
            if WOAptGet.is_installed(self, 'php8.1-fpm'):
                self.info_php81()
            else:
                Log.info(self, "PHP 8.1 is not installed")

        if pargs.mysql:
            if WOShellExec.cmd_exec(self, "/usr/bin/mysqladmin ping"):
                self.info_mysql()
            else:
                Log.info(self, "MySQL is not installed")
Exemple #21
0
    def removeconf(self, domain):
        sslconf = ("/var/www/{0}/conf/nginx/ssl.conf"
                   .format(domain))
        sslforce = ("/etc/nginx/conf.d/force-ssl-{0}.conf"
                    .format(domain))
        acmedir = [
            '{0}'.format(sslforce), '{0}'.format(sslconf),
            '{0}/{1}_ecc'.format(WOVar.wo_ssl_archive, domain),
            '{0}.disabled'.format(sslconf), '{0}.disabled'
            .format(sslforce), '{0}/{1}'
            .format(WOVar.wo_ssl_live, domain),
            '/etc/letsencrypt/shared/{0}.conf'.format(domain)]
        wo_domain = domain
        # check acme.sh is installed
        WOAcme.check_acme(self)
        if WOAcme.cert_check(self, wo_domain):
            Log.info(self, "Removing Acme configuration")
            Log.debug(self, "Removing Acme configuration")
            try:
                WOShellExec.cmd_exec(
                    self, "{0} ".format(WOAcme.wo_acme_exec) +
                    "--remove -d {0} --ecc".format(domain))
            except CommandExecutionError as e:
                Log.debug(self, "{0}".format(e))
                Log.error(self, "Cert removal failed")
            # remove all files and directories
            for dir in acmedir:
                if os.path.exists('{0}'.format(dir)):
                    WOFileUtils.rm(self, '{0}'.format(dir))
            # find all broken symlinks
            WOFileUtils.findBrokenSymlink(self, "/var/www")
        else:
            if os.path.islink("{0}".format(sslconf)):
                WOFileUtils.remove_symlink(self, "{0}".format(sslconf))
                WOFileUtils.rm(self, '{0}'.format(sslforce))

        if WOFileUtils.grepcheck(self, '/var/www/22222/conf/nginx/ssl.conf',
                                 '{0}'.format(domain)):
            Log.info(
                self, "Setting back default certificate for WordOps backend")
            with open("/var/www/22222/conf/nginx/"
                      "ssl.conf", "w") as ssl_conf_file:
                ssl_conf_file.write("ssl_certificate "
                                    "/var/www/22222/cert/22222.crt;\n"
                                    "ssl_certificate_key "
                                    "/var/www/22222/cert/22222.key;\n")
Exemple #22
0
    def setupletsencrypt(self, acme_domains, acmedata):
        """Issue SSL certificates with acme.sh"""
        # check acme.sh is installed
        WOAcme.check_acme(self)
        # define variables
        all_domains = '\' -d \''.join(acme_domains)
        wo_acme_dns = acmedata['acme_dns']
        keylenght = acmedata['keylength']
        if acmedata['dns'] is True:
            acme_mode = "--dns {0}".format(wo_acme_dns)
            validation_mode = "DNS mode with {0}".format(wo_acme_dns)
            if acmedata['dnsalias'] is True:
                acme_mode = acme_mode + \
                    " --challenge-alias {0}".format(acmedata['acme_alias'])
        else:
            acme_mode = "-w /var/www/html"
            validation_mode = "Webroot challenge"
            Log.debug(self, "Validation : Webroot mode")
            if not os.path.isdir('/var/www/html/.well-known/acme-challenge'):
                WOFileUtils.mkdir(self,
                                  '/var/www/html/.well-known/acme-challenge')
            WOFileUtils.chown(self,
                              '/var/www/html/.well-known',
                              'www-data',
                              'www-data',
                              recursive=True)
            WOFileUtils.chmod(self,
                              '/var/www/html/.well-known',
                              0o750,
                              recursive=True)

        Log.info(self, "Validation mode : {0}".format(validation_mode))
        Log.wait(self, "Issuing SSL cert with acme.sh")
        if not WOShellExec.cmd_exec(
                self, "{0} ".format(WOAcme.wo_acme_exec) +
                "--issue -d '{0}' {1} -k {2} -f".format(
                    all_domains, acme_mode, keylenght)):
            Log.failed(self, "Issuing SSL cert with acme.sh")
            if acmedata['dns'] is True:
                Log.error(
                    self, "Please make sure your properly "
                    "set your DNS API credentials for acme.sh\n"
                    "If you are using sudo, use \"sudo -E wo\"")
                return False
            else:
                Log.error(
                    self, "Your domain is properly configured "
                    "but acme.sh was unable to issue certificate.\n"
                    "You can find more informations in "
                    "/var/log/wo/wordops.log")
                return False
        else:
            Log.valide(self, "Issuing SSL cert with acme.sh")
            return True
Exemple #23
0
    def debug_mysql(self):
        """Start/Stop MySQL debug"""
        # MySQL start global debug
        if (self.app.pargs.mysql == 'on' and not self.app.pargs.site_name):
            if not WOShellExec.cmd_exec(
                    self, "mysql -e \"show variables like"
                    " \'slow_query_log\';\" | "
                    "grep ON"):
                Log.info(self, "Setting up MySQL slow log")
                WOMysql.execute(self, "set global slow_query_log = " "\'ON\';")
                WOMysql.execute(
                    self, "set global slow_query_log_file = "
                    "\'/var/log/mysql/mysql-slow.log\';")
                WOMysql.execute(self, "set global long_query_time = 2;")
                WOMysql.execute(
                    self, "set global log_queries_not_using"
                    "_indexes = \'ON\';")
            else:
                Log.info(self, "MySQL slow log is already enabled")

            self.msg = self.msg + ['/var/log/mysql/mysql-slow.log']

        # MySQL stop global debug
        elif (self.app.pargs.mysql == 'off' and not self.app.pargs.site_name):
            if WOShellExec.cmd_exec(
                    self, "mysql -e \"show variables like \'"
                    "slow_query_log\';\" | grep ON"):
                Log.info(self, "Disabling MySQL slow log")
                WOMysql.execute(self, "set global slow_query_log = \'OFF\';")
                WOMysql.execute(
                    self, "set global slow_query_log_file = \'"
                    "/var/log/mysql/mysql-slow.log\';")
                WOMysql.execute(self, "set global long_query_time = 10;")
                WOMysql.execute(
                    self, "set global log_queries_not_using_index"
                    "es = \'OFF\';")
                WOShellExec.cmd_exec(
                    self, "crontab -l | sed \'/#WordOps "
                    "start/,/#WordOps end/d\' | crontab -")
            else:
                Log.info(self, "MySQL slow log already disabled")
Exemple #24
0
 def export_cert(self):
     """Export acme.sh csv certificate list"""
     # check acme.sh is installed
     WOAcme.check_acme(self)
     acme_list = WOShellExec.cmd_exec_stdout(
         self, "{0} ".format(WOAcme.wo_acme_exec) +
         "--list --listraw")
     if acme_list:
         WOFileUtils.textwrite(self, '/var/lib/wo/cert.csv', acme_list)
         WOFileUtils.chmod(self, '/var/lib/wo/cert.csv', 0o600)
     else:
         Log.error(self, "Unable to export certs list")
Exemple #25
0
    def add(self):
        """Swap addition with WordOps"""
        # Get System RAM and SWAP details
        wo_ram = psutil.virtual_memory().total / (1024 * 1024)
        wo_swap = psutil.swap_memory().total / (1024 * 1024)
        if wo_ram < 512:
            if wo_swap < 1000:
                Log.info(self, "Adding SWAP file, please wait...")

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

                # Modify Swap configuration
                if os.path.isfile("/etc/dphys-swapfile"):
                    WOFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                              "#CONF_SWAPFILE=/var/swap",
                                              "CONF_SWAPFILE=/wo-swapfile")
                    WOFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                              "#CONF_MAXSWAP=2048",
                                              "CONF_MAXSWAP=1024")
                    WOFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                              "#CONF_SWAPSIZE=",
                                              "CONF_SWAPSIZE=1024")
                else:
                    with open("/etc/dphys-swapfile", 'w') as conffile:
                        conffile.write("CONF_SWAPFILE=/wo-swapfile\n"
                                       "CONF_SWAPSIZE=1024\n"
                                       "CONF_MAXSWAP=1024\n")
                # Create swap file
                WOShellExec.cmd_exec(self, "service dphys-swapfile start")
Exemple #26
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/" +
                              WOVar().wo_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:
            ppa_split = ppa.split(':')[1]
            ppa_author = ppa_split.split('/')[0]
            Log.debug(self, "ppa_author = {0}".format(ppa_author))
            ppa_package = ppa_split.split('/')[1]
            Log.debug(self, "ppa_package = {0}".format(ppa_package))
            if os.path.exists(
                '/etc/apt/sources.list.d/{0}-ubuntu-{1}-{2}.list'
                    .format(ppa_author,
                            ppa_package, WOVar.wo_platform_codename)):
                Log.debug(self, "ppa already added")
                return True
            if WOShellExec.cmd_exec(
                    self, "LC_ALL=C.UTF-8 add-apt-repository -y '{ppa_name}'"
                    .format(ppa_name=ppa)):
                Log.debug(self, "Added PPA {0}".format(ppa))
                return True
        return False
Exemple #27
0
    def checkwildcardexist(self, wo_domain_name):
        """Check if a wildcard certificate exist for a domain"""

        wo_acme_exec = ("/etc/letsencrypt/acme.sh --config-home "
                        "'/etc/letsencrypt/config'")
        # export certificates list from acme.sh
        WOShellExec.cmd_exec(
            self, "{0} ".format(wo_acme_exec) +
            "--list --listraw > /var/lib/wo/cert.csv")

        # define new csv dialect
        csv.register_dialect('acmeconf', delimiter='|')
        # open file
        certfile = open('/var/lib/wo/cert.csv', mode='r', encoding='utf-8')
        reader = csv.reader(certfile, 'acmeconf')
        wo_wildcard_domain = ("*.{0}".format(wo_domain_name))
        for row in reader:
            if wo_wildcard_domain == row[2]:
                if not row[3] == "":
                    return True
        certfile.close()
        return False
Exemple #28
0
    def default(self):
        pargs = self.app.pargs
        if not pargs.site_name:
            try:
                while not pargs.site_name:
                    pargs.site_name = (input('Enter site name : ').strip())
            except IOError as e:
                Log.debug(self, str(e))
                Log.error(self, 'Unable to read input, Please try again')

        pargs.site_name = pargs.site_name.strip()
        wo_domain = WODomain.validate(self, pargs.site_name)
        wo_www_domain = "www.{0}".format(wo_domain)
        if not check_domain_exists(self, wo_domain):
            Log.error(self, "site {0} does not exist".format(wo_domain))

        wo_site_webroot = WOVar.wo_webroot + wo_domain

        if os.path.isfile('/etc/nginx/sites-available/{0}'.format(wo_domain)):
            try:
                WOShellExec.invoke_editor(
                    self, '/etc/nginx/sites-availa'
                    'ble/{0}'.format(wo_domain))
            except CommandExecutionError as e:
                Log.debug(self, str(e))
                Log.error(self, "Failed invoke editor")
            if (WOGit.checkfilestatus(
                    self, "/etc/nginx",
                    '/etc/nginx/sites-available/{0}'.format(wo_domain))):
                WOGit.add(self, ["/etc/nginx"],
                          msg="Edit website: {0}".format(wo_domain))
                # Reload NGINX
                if not WOService.reload_service(self, 'nginx'):
                    Log.error(
                        self, "service nginx reload failed. "
                        "check issues with `nginx -t` command")
        else:
            Log.error(self, "nginx configuration file does not exists")
Exemple #29
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/" +
                              WOVariables().wo_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:
            WOShellExec.cmd_exec(
                self,
                "add-apt-repository -yu '{ppa_name}'".format(ppa_name=ppa))
Exemple #30
0
 def secure_ssh_port(self):
     """Change SSH port"""
     WOGit.add(self, ["/etc/ssh"],
               msg="Adding changed SSH port into Git")
     pargs = self.app.pargs
     if pargs.user_input:
         while ((not pargs.user_input.isdigit()) and
                (not pargs.user_input < 65536)):
             Log.info(self, "Please enter a valid port number ")
             pargs.user_input = input("Server "
                                      "SSH port [22]:")
     if not pargs.user_input:
         port = input("Server SSH port [22]:")
         if port == "":
             port = 22
         while (not port.isdigit()) and (port != "") and (not port < 65536):
             Log.info(self, "Please Enter valid port number :")
             port = input("Server SSH port [22]:")
         pargs.user_input = port
     if WOFileUtils.grepcheck(self, '/etc/ssh/sshd_config', '#Port'):
         WOShellExec.cmd_exec(self, "sed -i \"s/#Port.*/Port "
                              "{port}/\" /etc/ssh/sshd_config"
                              .format(port=pargs.user_input))
     else:
         WOShellExec.cmd_exec(self, "sed -i \"s/Port.*/Port "
                              "{port}/\" /etc/ssh/sshd_config"
                              .format(port=pargs.user_input))
     # allow new ssh port if ufw is enabled
     if os.path.isfile('/etc/ufw/ufw.conf'):
         # add rule for proftpd with UFW
         if WOFileUtils.grepcheck(
                 self, '/etc/ufw/ufw.conf', 'ENABLED=yes'):
             try:
                 WOShellExec.cmd_exec(
                     self, 'ufw limit {0}'.format(pargs.user_input))
                 WOShellExec.cmd_exec(
                     self, 'ufw reload')
             except Exception as e:
                 Log.debug(self, "{0}".format(e))
                 Log.error(self, "Unable to add UFW rule")
     # add ssh into git
     WOGit.add(self, ["/etc/ssh"],
               msg="Adding changed SSH port into Git")
     # restart ssh service
     if not WOService.restart_service(self, 'ssh'):
         Log.error(self, "service SSH restart failed.")
     Log.info(self, "Successfully changed SSH port to {port}"
              .format(port=pargs.user_input))