How to use the certbot.compat.os.path.basename function in certbot

To help you get started, we’ve selected a few certbot examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github certbot / certbot / certbot / certbot / _internal / hooks.py View on Github external
def execute(cmd_name, shell_cmd):
    """Run a command.

    :param str cmd_name: the user facing name of the hook being run
    :param shell_cmd: shell command to execute
    :type shell_cmd: `list` of `str` or `str`

    :returns: `tuple` (`str` stderr, `str` stdout)"""
    logger.info("Running %s command: %s", cmd_name, shell_cmd)

    # universal_newlines causes Popen.communicate()
    # to return str objects instead of bytes in Python 3
    cmd = Popen(shell_cmd, shell=True, stdout=PIPE,
                stderr=PIPE, universal_newlines=True)
    out, err = cmd.communicate()
    base_cmd = os.path.basename(shell_cmd.split(None, 1)[0])
    if out:
        logger.info('Output from %s command %s:\n%s', cmd_name, base_cmd, out)
    if cmd.returncode != 0:
        logger.error('%s command "%s" returned error code %d',
                     cmd_name, shell_cmd, cmd.returncode)
    if err:
        logger.error('Error output from %s command %s:\n%s', cmd_name, base_cmd, err)
    return err, out
github certbot / certbot / certbot-apache / certbot_apache / _internal / configurator.py View on Github external
def _get_ssl_vhost_path(self, non_ssl_vh_fp):
        """ Get a file path for SSL vhost, uses user defined path as priority,
        but if the value is invalid or not defined, will fall back to non-ssl
        vhost filepath.

        :param str non_ssl_vh_fp: Filepath of non-SSL vhost

        :returns: Filepath for SSL vhost
        :rtype: str
        """

        if self.conf("vhost-root") and os.path.exists(self.conf("vhost-root")):
            fp = os.path.join(filesystem.realpath(self.option("vhost_root")),
                              os.path.basename(non_ssl_vh_fp))
        else:
            # Use non-ssl filepath
            fp = filesystem.realpath(non_ssl_vh_fp)

        if fp.endswith(".conf"):
            return fp[:-(len(".conf"))] + self.option("le_vhost_ext")
        return fp + self.option("le_vhost_ext")
github certbot / certbot / certbot-apache / certbot_apache / configurator.py View on Github external
objects found in configuration
        :rtype: list

        """
        # Search base config, and all included paths for VirtualHosts
        file_paths = {}  # type: Dict[str, str]
        internal_paths = defaultdict(set)  # type: DefaultDict[str, Set[str]]
        vhs = []
        # Make a list of parser paths because the parser_paths
        # dictionary may be modified during the loop.
        for vhost_path in list(self.parser.parser_paths):
            paths = self.parser.aug.match(
                ("/files%s//*[label()=~regexp('%s')]" %
                    (vhost_path, parser.case_i("VirtualHost"))))
            paths = [path for path in paths if
                     "virtualhost" in os.path.basename(path).lower()]
            for path in paths:
                new_vhost = self._create_vhost(path)
                if not new_vhost:
                    continue
                internal_path = apache_util.get_internal_aug_path(new_vhost.path)
                realpath = filesystem.realpath(new_vhost.filep)
                if realpath not in file_paths:
                    file_paths[realpath] = new_vhost.filep
                    internal_paths[realpath].add(internal_path)
                    vhs.append(new_vhost)
                elif (realpath == new_vhost.filep and
                      realpath != file_paths[realpath]):
                    # Prefer "real" vhost paths instead of symlinked ones
                    # ex: sites-enabled/vh.conf -> sites-available/vh.conf

                    # remove old (most likely) symlinked one
github certbot / certbot / certbot / certbot / reverter.py View on Github external
def _checkpoint_timestamp(self):
        "Determine the timestamp of the checkpoint, enforcing monotonicity."
        timestamp = str(time.time())
        others = glob.glob(os.path.join(self.config.backup_dir, "[0-9]*"))
        others = [os.path.basename(d) for d in others]
        others.append(timestamp)
        others.sort()
        if others[-1] != timestamp:
            timetravel = str(float(others[-1]) + 1)
            logger.warning("Current timestamp %s does not correspond to newest reverter "
                "checkpoint; your clock probably jumped. Time travelling to %s",
                timestamp, timetravel)
            timestamp = timetravel
        elif len(others) > 1 and others[-2] == timestamp:
            # It is possible if the checkpoints are made extremely quickly
            # that will result in a name collision.
            logger.debug("Race condition with timestamp %s, incrementing by 0.01", timestamp)
            timetravel = str(float(others[-1]) + 0.01)
            timestamp = timetravel
        return timestamp
github certbot / certbot / certbot-apache / certbot_apache / _internal / display_ops.py View on Github external
filename_size = int(free_chars * .6)
        disp_name_size = free_chars - filename_size

    choices = []
    for vhost in vhosts:
        if len(vhost.get_names()) == 1:
            disp_name = next(iter(vhost.get_names()))
        elif not vhost.get_names():
            disp_name = ""
        else:
            disp_name = "Multiple Names"

        choices.append(
            "{fn:{fn_size}s} | {name:{name_size}s} | {https:5s} | "
            "{active:7s}".format(
                fn=os.path.basename(vhost.filep)[:filename_size],
                name=disp_name[:disp_name_size],
                https="HTTPS" if vhost.ssl else "",
                active="Enabled" if vhost.enabled else "",
                fn_size=filename_size,
                name_size=disp_name_size)
        )

    try:
        code, tag = zope.component.getUtility(interfaces.IDisplay).menu(
            "We were unable to find a vhost with a ServerName "
            "or Address of {0}.{1}Which virtual host would you "
            "like to choose?".format(domain, os.linesep),
            choices, force_interactive=True)
    except errors.MissingCommandlineFlag:
        msg = (
            "Encountered vhost ambiguity when trying to find a vhost for "
github certbot / certbot / certbot / _internal / storage.py View on Github external
def _update_symlinks(self):
        """Updates symlinks to use archive_dir"""
        for kind in ALL_FOUR:
            link = getattr(self, kind)
            previous_link = get_link_target(link)
            new_link = os.path.join(self.relative_archive_dir(link),
                os.path.basename(previous_link))

            os.unlink(link)
            os.symlink(new_link, link)
github certbot / certbot / certbot-apache / certbot_apache / _internal / parser.py View on Github external
def _check_path_actions(self, filepath):
        """Determine actions to take with a new augeas path

        This helper function will return a tuple that defines
        if we should try to append the new filepath to augeas
        parser paths, and / or remove the old one with more
        narrow matching.

        :param str filepath: filepath to check the actions for

        """

        try:
            new_file_match = os.path.basename(filepath)
            existing_matches = self.parser_paths[os.path.dirname(filepath)]
            if "*" in existing_matches:
                use_new = False
            else:
                use_new = True
            remove_old = new_file_match == "*"
        except KeyError:
            use_new = True
            remove_old = False
        return use_new, remove_old
github certbot / certbot / certbot-apache / certbot_apache / _internal / configurator.py View on Github external
objects found in configuration
        :rtype: list

        """
        # Search base config, and all included paths for VirtualHosts
        file_paths = {}  # type: Dict[str, str]
        internal_paths = defaultdict(set)  # type: DefaultDict[str, Set[str]]
        vhs = []
        # Make a list of parser paths because the parser_paths
        # dictionary may be modified during the loop.
        for vhost_path in list(self.parser.parser_paths):
            paths = self.parser.aug.match(
                ("/files%s//*[label()=~regexp('%s')]" %
                    (vhost_path, parser.case_i("VirtualHost"))))
            paths = [path for path in paths if
                     "virtualhost" in os.path.basename(path).lower()]
            for path in paths:
                new_vhost = self._create_vhost(path)
                if not new_vhost:
                    continue
                internal_path = apache_util.get_internal_aug_path(new_vhost.path)
                realpath = filesystem.realpath(new_vhost.filep)
                if realpath not in file_paths:
                    file_paths[realpath] = new_vhost.filep
                    internal_paths[realpath].add(internal_path)
                    vhs.append(new_vhost)
                elif (realpath == new_vhost.filep and
                      realpath != file_paths[realpath]):
                    # Prefer "real" vhost paths instead of symlinked ones
                    # ex: sites-enabled/vh.conf -> sites-available/vh.conf

                    # remove old (most likely) symlinked one
github certbot / certbot / certbot / _internal / storage.py View on Github external
"the archive directory in the renewal configuration "
                             "file, you may need to update links by running "
                             "certbot update_symlinks.",
                             link, os.path.dirname(target), self.archive_dir)
                return False

            # The link must point to a file that exists
            if not os.path.exists(target):
                logger.debug("Link %s points to file %s that does not exist.",
                             link, target)
                return False

            # The link must point to a file that follows the archive
            # naming convention
            pattern = re.compile(r"^{0}([0-9]+)\.pem$".format(kind))
            if not pattern.match(os.path.basename(target)):
                logger.debug("%s does not follow the archive naming "
                             "convention.", target)
                return False

            # It is NOT required that the link's target be a regular
            # file (it may itself be a symlink). But we should probably
            # do a recursive check that ultimately the target does
            # exist?
        # XXX: Additional possible consistency checks (e.g.
        #      cryptographic validation of the chain being a chain,
        #      the chain matching the cert, and the cert matching
        #      the subject key)
        # XXX: All four of the targets are in the same directory
        #      (This check is redundant with the check that they
        #      are all in the desired directory!)
        #      len(set(os.path.basename(self.current_target(x)