Beispiel #1
0
def cargar_paquete():
    try:
        # Prueba a importar el paquete distro
        from distro import like, id as distro_id
    except:
        # En caso de no poder muetra un mensaje y cierra la aplicacion
        print(Colores.AZUL + "El paquete " + Colores.VERDE + "distro " +
              Colores.AZUL + "no esta instalado" + Colores.FINC)
        exit(
            1
        )  # Funcion que determina el comportamiento del codigo en un error

    # Comprueba si la distribucion deriva de otra y si se encuentra en el objeto de sistema_paquetes
    if like() and like() in sistema_paquetes:
        # Guarda los comandos en la variable paquete
        paquete = sistema_paquetes.get(like().lower())
    # Comprueba si el id de la distribucion se encuentra en el objeto de sistema_paquetes
    elif distro_id() in sistema_paquetes:
        # Guarda los comandos en la variable paquete
        paquete = sistema_paquetes.get(distro_id().lower())
    else:
        # En caso de que la distribucion no se encuentre en sistema_paquetes, muestra un mensaje y cierra la apliación
        print(Colores.AZUL + "El sistema de archivos de la distribucion" +
              Colores.VERDE + distro_id() + Colores.AZUL +
              " no esta soportado" + Colores.FINC)
        exit(1)

    # Devuelve la variable con los comandos
    return paquete
Beispiel #2
0
    def _lookup_by_mapping():
        """Returns a tuple containing the init system's type and version based
        on a constant mapping of distribution+version to init system..

        See constants.py for the mapping.
        A failover of the version is proposed for when no version is supplied.
        For instance, Arch Linux's version will most probably be "rolling" at
        any given time, which means that the init system cannot be idenfied
        by the version of the distro.

        On top of trying to identify by the distro's ID, if /etc/os-release
        contains an "ID_LIKE" field, it will be tried. That, again is true
        for Arch where the distro's ID changes (Manjaro, Antergos, etc...)
        But the "ID_LIKE" field is always (?) `arch`.
        """
        like = distro.like().lower()
        distribution_id = distro.id().lower()
        version = distro.major_version()
        # init (upstart 1.12.1)
        if distribution_id in ('arch'):
            version = 'any'
        if like in ('arch'):
            version = 'any'
        init_sys = const.DIST_TO_INITSYS.get(
            distribution_id, const.DIST_TO_INITSYS.get(like))
        if init_sys:
            return [init_sys.get(version)] or []
Beispiel #3
0
def os_release():
    """
    This code detects your os with the distro module and return the name and version. If it is not detected correctly it
    returns "unknown" (str) and "0" (float).
    @:returns tuple (str, float)
        WHERE
        str is the name
        int is the version number
    """
    distroname = distro.id()
    distrolike = distro.like()
    version = distro.version()

    redhat = ["centos", "fedora", "rhel"]

    if distroname in redhat or distrolike in redhat:
        if distroname in ["centos", "fedora"]:
            return distroname, float(version)
        else:
            return "redhat", float(version)

    if distroname is ["debian", "ubuntu"]:
        return distroname, float(version)

    if distrolike == "suse":
        return "suse", float(version)

    return "unknown", 0.0
Beispiel #4
0
    def _detection_logic():
        """Main distribution detection logic, relying on `distro`, handling _common_ cases"""
        # Are we running on Windows ?
        if sys.platform in ('win32', 'cygwin'):
            return Distributions.WINDOWS

        # Is it a Windows Sub-system Linux (WSL) distribution ?
        # If so, kernel release identifier should keep a trace of it.
        if b'microsoft' in check_output(['uname', '-r']).lower():
            return Distributions.WINDOWS

        # Is `ID` (from `os-release`) well-known and supported ?
        try:
            return Distributions(distro.id())
        except ValueError:
            pass

        # Is any of `ID_LIKE` (from `os-release`) well-known and supported ?
        # See <https://www.freedesktop.org/software/systemd/man/os-release.html#ID_LIKE=>.
        for id_like in distro.like().split(' '):
            try:
                return Distributions(id_like)
            except ValueError:
                pass

        # Nothing of the above matched, let's return `None` and let the caller handle it.
        return None
Beispiel #5
0
def _system_info():
    system = platform.system()

    if system == "Windows":
        version = sys.getwindowsversion()

        return {
            "os": "windows",
            "windows_version_build": version.build,
            "windows_version_major": version.major,
            "windows_version_minor": version.minor,
            "windows_version_service_pack": version.service_pack,
        }

    if system == "Darwin":
        return {"os": "mac", "mac_version": platform.mac_ver()[0]}

    if system == "Linux":
        return {
            "os": "linux",
            "linux_distro": distro.id(),
            "linux_distro_like": distro.like(),
            "linux_distro_version": distro.version(),
        }

    # We don't collect data for any other system.
    raise NotImplementedError
    def __parse_contents(self) -> bool:
        """
        Use both distro.id and distro.like to accurately
        get the users distribution or parent distribution
        """
        try:
            json_data: Dict[str, Any] = self.__load_file()
            if not json_data:
                return False
            distro_data: Dict[str, Any] = json_data["distros"]
            self.python_dependencies = json_data["python-deps"]
            self.rust_dependencies = json_data["rust-deps"]

            for distro_type, pkgman in distro_data.items():
                if distro_type == distro.id() or distro_type in distro.like(
                ).split():
                    self.distro = distro.id()
                    for key, value in pkgman.items():
                        self.pkgmanager = key
                        self.install_commands = value["cmd"]
                        self.dependencies = value["deps"]
        except KeyError:
            return False

        return True
Beispiel #7
0
    def __init__(self) -> None:
        """
        Creates a new HostDistribution instance.
        """

        try:
            import distro
            self._id = distro.id()
            self._name = distro.name(pretty=False)
            self._fullname = distro.name(pretty=True)

            try:
                self._major = int(distro.major_version())
            except ValueError:
                self._major = -1

            try:
                self._minor = int(distro.minor_version())
            except ValueError:
                self._minor = -1

            try:
                self._build = int(distro.build_number())
            except ValueError:
                self._build = -1

            self._versionstring = distro.version(pretty=False)
            self._codename = distro.codename()
            self._like = distro.like()
        except ImportError:
            from suisei.murasame.exceptions import MissingRequirementError
            raise MissingRequirementError(
                'HostDistribution requires the distro package.',
                requirement='distro')
Beispiel #8
0
    def __init__(self):
        # First we check whether the Kernel has been compiled as a WSL.
        if 'microsoft' in check_output(['uname', '-r'],
                                       universal_newlines=True).lower():
            self._distribution = Distributions.WINDOWS
        else:
            try:
                self._distribution = Distributions(distro.id())
            except ValueError:
                # See <https://www.freedesktop.org/software/systemd/man/os-release.html#ID_LIKE=>.
                for distro_like in distro.like().split(' '):
                    try:
                        self._distribution = Distributions(distro_like)
                    except ValueError:
                        continue
                    break
                else:
                    # Well, we didn't match anything so let's fall-back to default `Linux`.
                    self._distribution = Distributions.LINUX

        # Fetch the colors palette related to this distribution.
        self._colors_palette = COLOR_DICT[self._distribution]

        # If `os-release`'s `ANSI_COLOR` option is set, honor it.
        # See <https://www.freedesktop.org/software/systemd/man/os-release.html#ANSI_COLOR=>.
        ansi_color = distro.os_release_attr('ansi_color')
        if ansi_color and Configuration().get(
                'colors_palette')['honor_ansi_color']:
            # Replace each Archey integrated colors by `ANSI_COLOR`.
            self._colors_palette = len(self._colors_palette) * \
                [Colors.escape_code_from_attrs(ansi_color)]

        # Each class output will be added in the list below afterwards
        self._results = []
Beispiel #9
0
def test():
    """
    Returns:
        A dict of system information.
    """
    os = platform.system()
    if os == "Darwin":
        return {"os": "mac", "mac_version": platform.mac_ver()[0]}

    if os == "Windows":
        release, version, csd, platform_type = platform.win32_ver()
        return {
            "os": "windows",
            "windows_version_release": release,
            "windows_version": version,
            "windows_version_service_pack": csd,
            "windows_version_os_type": platform_type,
        }

    if os == "Linux":
        return {
            "os": "linux",
            "linux_distro": distro.id(),
            "linux_distro_like": distro.like(),
            "linux_distro_version": distro.version(),
        }

    return {"os": os}
Beispiel #10
0
def get_system_info() -> Dict[str, Any]:
    """Returns system info as a dict.

    Returns:
        A dict of system information.
    """
    system = platform.system()

    if system == "Windows":
        release, version, csd, ptype = platform.win32_ver()

        return {
            "os": "windows",
            "windows_version_release": release,
            "windows_version": version,
            "windows_version_service_pack": csd,
            "windows_version_os_type": ptype,
        }

    if system == "Darwin":
        return {"os": "mac", "mac_version": platform.mac_ver()[0]}

    if system == "Linux":
        return {
            "os": "linux",
            "linux_distro": distro.id(),
            "linux_distro_like": distro.like(),
            "linux_distro_version": distro.version(),
        }

    # We don't collect data for any other system.
    return {"os": "unknown"}
Beispiel #11
0
 def _collect_linux(self):
     import distro
     info = {}
     info[self.PARAM_OS] = 'linux'
     info[self.PARAM_LINUX_DISTRO] = distro.id()
     info[self.PARAM_LINUX_DISTRO_VERSION] = distro.version()
     info[self.PARAM_LINUX_DISTRO_LIKE] = distro.like()
     return info
Beispiel #12
0
 def _pm_autodetect(self):
     if self.packagemanager == 'autodetect':
         current_distro = distro.like()
         if current_distro == '':
             current_distro = distro.id()
         if current_distro in ['debian', 'ubuntu']:
             self.packagemanager = 'apt'
         elif current_distro == 'arch':
             self.packagemanager = 'pacman'
Beispiel #13
0
def detect_profile():
    try:
        import distro

        target = distro.id()
        if not target in get_possible_profiles():
            target = distro.like()
    except ModuleNotFoundError:
        target = ""
    return target
Beispiel #14
0
def detect_distro():  # pragma: no cover
    """
    Detects the distro name
    :returns: The name of the distro see `here <http://distro.readthedocs.io/en/latest/>`_
    :rtype: str
    """
    distro_name = distro.like()
    if not distro_name:
        distro_name = distro.id()
    Logger.logger.info("Detected distro:\t" + distro_name)
    return distro_name
Beispiel #15
0
def get_from_linux():
    commands = {
        'debian': ('dpkg', '-l'),
        'ubuntu': ('dpkg', '-l'),
        'fedora': ('rpm', '-qa'),
        'arch': ('pacman', '-Q'),
        'slackware': ('slapt-get', '--installed')
    }

    linux_distro = distro.linux_distribution(full_distribution_name=False)[0]
    like_distro = distro.like()
    def _collect_os_default(self):
        os_info = dict()
        os_info["system"] = platform.system()
        os_info["release"] = platform.release()
        os_info["like"] = distro.like()
        os_info["build_number"] = distro.build_number()
        os_info["version"] = distro.version()
        os_info["name"] = distro.name()
        os_info["codename"] = distro.codename()

        self._logger.debug(os_info)
        return os_info
Beispiel #17
0
def is_ovirt_packaging_supported_distro():
    """Return True if running on a Linux Distribution supported by oVirt
    packaging. In the past, also gentoo was supported by oVirt, only in
    developer-mode.
    """
    # Previously, we used platform.linux_distribution, but this was removed
    # in Python 3.8: https://bugs.python.org/issue1322
    # Also, it does not include 'like' or 'variety'.
    # Python 3.10 added Add platform.freedesktop_os_release, but we can't use
    # that, as EL8 has 3.6. So we rely for now on pypi's 'distro'.
    id_and_like = [distro.id()] + distro.like().split(' ')
    return any(dist in id_and_like for dist in ('rhel', 'fedora'))
Beispiel #18
0
def get_systemd_os_like():
    """
    Get a list of strings that indicate the distribution likeness to
    other distributions.

    :returns: List of distribution acronyms
    :rtype: `list` of `str`
    """

    if _USE_DISTRO:
        return distro.like().split(" ")
    return []
Beispiel #19
0
    def __init__(self, realm, warnings=False, debug=False):
        self.warnings = warnings
        self.realm = realm.upper()
        self.krb_prefix = ""
        sep = os.path.sep
        # For the future if we have a non-os krb install.
        if 'suse' in distro.like():
            self.kadmin = os.path.join(sep, self.krb_prefix,
                                       "usr/lib/mit/sbin/kadmin.local")
            self.kdb5_util = os.path.join(sep, self.krb_prefix,
                                          "usr/lib/mit/sbin/kdb5_util")
            self.krb5kdc = os.path.join(sep, self.krb_prefix,
                                        "usr/lib/mit/sbin/krb5kdc")
            self.kdcconf = os.path.join(sep, self.krb_prefix,
                                        "var/lib/kerberos/krb5kdc/kdc.conf")
            self.kadm5acl = os.path.join(sep, self.krb_prefix,
                                         "var/lib/kerberos/krb5kdc/kadm5.acl")
            self.kadm5keytab = os.path.join(
                sep, self.krb_prefix, "var/lib/kerberos/krb5kdc/kadm5.keytab")
            self.kdcpid = os.path.join(sep, self.krb_prefix,
                                       "var/run/krb5kdc.pid")
            self.krb5conf = os.path.join(sep, self.krb_prefix, "etc/krb5.conf")
            self.krb5confrealm = os.path.join(
                sep, self.krb_prefix, "etc/krb5.conf.d",
                self.realm.lower().replace('.', '-'))
        else:
            self.kadmin = os.path.join(sep, self.krb_prefix,
                                       "usr/sbin/kadmin.local")
            self.kdb5_util = os.path.join(sep, self.krb_prefix,
                                          "usr/sbin/kdb5_util")
            self.krb5kdc = os.path.join(sep, self.krb_prefix,
                                        "usr/sbin/krb5kdc")
            self.kdcconf = os.path.join(sep, self.krb_prefix,
                                        "var/kerberos/krb5kdc/kdc.conf")
            self.kadm5acl = os.path.join(sep, self.krb_prefix,
                                         "var/kerberos/krb5kdc/kadm5.acl")
            self.kadm5keytab = os.path.join(
                sep, self.krb_prefix, "var/kerberos/krb5kdc/kadm5.keytab")
            self.kdcpid = os.path.join(sep, self.krb_prefix,
                                       "var/run/krb5kdc.pid")
            self.krb5conf = os.path.join(sep, self.krb_prefix, "etc/krb5.conf")
            self.krb5confrealm = os.path.join(
                sep, self.krb_prefix, "etc/krb5.conf.d",
                self.realm.lower().replace('.', '-'))

        self.krb_primary_password = password_generate()

        # Should we write this to a file?

        self.krb_env = {}
        if debug is True:
            self.krb_env['KRB5_TRACE'] = '/tmp/krb_lib389.trace'
Beispiel #20
0
def is_redhat():
    try:
        from platform import linux_distribution
    except ImportError as ex:
        # Since Python 3.8 linux_distribution has been removed
        try:
            import distro
        except ImportError as ex:
            warnings.warn(str(ex))
            return False  # this is fine in most of the cases
        else:
            return 'rhel' in distro.like().split()
    else:
        return 'redhat' in linux_distribution(supported_dists='redhat',
                                              full_distribution_name=False)
Beispiel #21
0
def get_pam_version():
    try:
        import platform
        linux_distro = platform.linux_distribution()[0].lower()
    except Exception:
        import distro
        linux_distro = distro.like()
    if linux_distro in ["ubuntu", "debian", "mint", "kali"]:
        return program_output(
            "dpkg -s libpam-modules | grep -i Version | awk '{ print $2 }'"
        ).split("-")[0]
    elif linux_distro in ["redhat", "centos", "centos linux"]:
        return program_output(
            "yum list installed | grep 'pam\.*' | awk '{print $2}'").split(
                "-")[0]
    return False
Beispiel #22
0
 def install():
     print(Y+"\nInstalling Metasploit-framework...\n"+W)
     premsf=['kali','parrot']
     deb=['ubuntu','debian']
     did=distro.like()
     did2=distro.id()
     print(did)
     
     if did in deb:
         if did in premsf:
             os.system("sudo apt-get upodate && sudo apt-get install metasploit-framework")
         else:
             os.system("sudo apt-get install -y build-essential zlib1g zlib1g-dev libpq-dev libpcap-dev libsqlite3-dev ruby ruby-dev")
             os.system("cd $HOME && git clone https://github.com/rapid7/metasploit-framework.git")
             os.system("cd $HOME/metasploit-framework && sudo gem install bundler && bundle install") 
             os.system("sudo cp assets/msfconsole /usr/bin/ && sudo cp assets/msfvenom /usr/bin/ && sudo cp assets/msfupdate /usr/bin/")
             os.system("clear")
     elif(did==""):
         print(Y+"\nOther distro detected ! Please install metasploit manually.\n"+W)
         exit(0)
     else:
         print(R+"\nSomething went wrong!\n"+W)
Beispiel #23
0
    def _vendor_detection() -> Optional['Distributions']:
        """Main distribution detection logic, relying on `distro`, handling _common_ cases"""
        # Are we running on Windows ?
        if platform.system() == 'Windows':
            return Distributions.WINDOWS

        # Is it a Windows Sub-system Linux (WSL) distribution ?
        # If so, kernel release identifier should keep a trace of it.
        if 'microsoft' in platform.release().lower():
            return Distributions.WINDOWS

        # Is `ID` (from `os-release`) well-known and supported ?
        with suppress(ValueError):
            return Distributions(distro.id())

        # Is any of `ID_LIKE` (from `os-release`) well-known and supported ?
        # See <https://www.freedesktop.org/software/systemd/man/os-release.html#ID_LIKE=>.
        for id_like in distro.like().split(' '):
            with suppress(ValueError):
                return Distributions(id_like)

        # Nothing of the above matched, let's return `None` and let the caller handle it.
        return None
    def __pre_reqs(self) -> None:
        """
        get the name of the users linux distribution,
        currently supporting only Debian bases, and Arch bases
        :return: None, exit with an error message if users distro is not supported
        """
        # see if the users distro is a debian or arch based system
        for distribution in distro.like().split(" "):
            if distribution in "debian":
                self.package_manager = "apt-get"
                self.distro_root = distribution
            if distribution in "arch":
                self.package_manager = "pacman"
                self.distro_root = distribution

        # if package_manager is empty, then the users distro is not a debian or arch base
        if not self.package_manager:
            self.error_msg(
                f"Your distro: {distro.name()} is not currently supported, "
                f"please open an issue for support, or submit a pr")

        self.info_msg(f"Found: {self.distro_root} based distro")
        self.info_msg(f"Setting package manager to: {self.package_manager}\n")
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import distro

print 'os_release_info: {0}'.format(distro.os_release_info())
print 'lsb_release_info: {0}'.format(distro.lsb_release_info())
print 'distro_release_info: {0}'.format(distro.distro_release_info())
print 'id: {0}'.format(distro.id())
print 'name: {0}'.format(distro.name())
print 'name_pretty: {0}'.format(distro.name(True))
print 'version: {0}'.format(distro.version())
print 'version_pretty: {0}'.format(distro.version(True))
print 'like: {0}'.format(distro.like())
print 'codename: {0}'.format(distro.codename())
print 'linux_distribution_full: {0}'.format(distro.linux_distribution())
print 'linux_distribution: {0}'.format(distro.linux_distribution(False))
print 'major_version: {0}'.format(distro.major_version())
print 'minor_version: {0}'.format(distro.minor_version())
print 'build_number: {0}'.format(distro.build_number())
Beispiel #26
0
# # Actual Setup.py Script ###########################################
#####################################################################

if __name__ == "__main__":
    # # Configurable installation roots for various data files.

    # Trailing slashes on these vars is to allow for easy
    # later configuration of relative paths if desired.
    docpath = "share/man"
    etcpath = "/etc/cobbler/"
    libpath = "/var/lib/cobbler/"
    logpath = "/var/log/"
    completion_path = "/usr/share/bash-completion/completions"
    statepath = "/tmp/cobbler_settings/devinstall"
    httpd_service = "httpd.service"
    suse_release = "suse" in distro.like()

    if suse_release:
        webconfig = "/etc/apache2/vhosts.d"
        webroot = "/srv/www/"
        http_user = "******"
        httpd_service = "apache2.service"
        defaultpath = "/etc/sysconfig/"
    elif os.path.exists("/etc/debian_version"):
        if os.path.exists("/etc/apache2/conf-available"):
            webconfig = "/etc/apache2/conf-available"
        else:
            webconfig = "/etc/apache2/conf.d"
        webroot = "/srv/www/"
        http_user = "******"
        defaultpath = "/etc/default/"
Beispiel #27
0
def get_id_like():
    like = distro.like()
    if not like:
        return None
    return like.split(' ')
Beispiel #28
0
def get_current_distro_like():
    if distro:
        return distro.like().split()
    else:
        return []
Beispiel #29
0
GREEN = colored.green
YELLOW = colored.yellow
distros = ["ubuntu", "debian", "linuxmint", "arch", "endeavouros"]
figlet = Figlet(font='speed')

print(YELLOW(figlet.renderText('''GAME SETUP''')))

while True:
    try:
        if platform.system() != 'Linux':
            print("This is for Linux only")
            break

        print("Detecting your distro...")
        # FIXME: Too many if-else..
        if distro.id() in distros or distro.like() in distros:
            print(
                GREEN(
                    f"[{distro.id()}] distro detected... based on {distro.like()}"
                ))
            if distro.id() == "ubuntu" or distro.like() == "ubuntu":
                sys_distro = 1
            elif distro.id() == "arch" or distro.like() == "arch":
                sys_distro = 2
            elif distro.id() == "debian" or distro.like(
            ) == "debian" and distro.id() != "ubuntu":
                sys_distro = 3
        else:
            sys_distro = 0

        print(
Beispiel #30
0
        print("\n")
        print("Caption: ", objItem.Caption)
        #print ("Description: ", objItem.Description)
        #print ("Identifying Number: ", objItem.IdentifyingNumber )
        #print ("Install Date: ", objItem.InstallDate )
        #print ("Install Date 2: ", objItem.InstallDate2 )
        #print ("Install Location: ", objItem.InstallLocation )
        #print ("Install State: ", objItem.InstallState )
        print("Name: ", objItem.Name)
        #print ("Package Cache: ", objItem.PackageCache )
        #print ("SKU Number: ", objItem.SKUNumber )
        print("Vendor: ", objItem.Vendor)
        print("Version: ", objItem.Version)
        print("\n")

elif platform.system() == "linux":
    if distro.like() == "ubuntu" or "debian":
        output = subprocess.check_output(
            "dpkg-query -f '${Package} ${Version}\n' -W", shell=True)
        output = output.decode("utf-8")
        print(output)
    """if distro.like() == "rhel":
        output = subprocess.check_output("dnf list installed", shell=True)
        output = output.decode("utf-8")
        print (output)"""

#p1 = subprocess.Popen(["apt","list", "--installed"], stdout=subprocess.PIPE)
#output = p1.communicate()[0]
#output = output.decode("utf-8")
#print (output)
Beispiel #31
0
 def get_series():
     series = distro.like()
     if not series:
         series = "UNKNOWN"
     return series
Beispiel #32
0
class Requirement():
    """
    Requirement parser
    """
    _parser = None
    _lookup: Dict[str, str] = dict(
        distro_codename=distro.codename(),
        distro_id=distro.id(),
        distro_like=distro.like(),
        distro_name=distro.name(),
        distro_version=distro.version(),
        os_name=os.name,
        platform_machine=platform.machine(),
        platform_python_implementation=platform.python_implementation(),
        platform_release=platform.release(),
        platform_system=platform.system(),
        platform_version=platform.version(),
        platform_full_version=platform.python_version(),
        python_version=platform.python_version()[:3],
        sys_platform=sys.platform)

    def __init__(self, s):
        self._parser = parsley.makeGrammar(
            GRAMMAR, {"lookup": self._lookup.__getitem__})
        self._parsed_requirement = self._parser(s).specification()

    @property
    def name(self):
        """
        Get the name part of the requirement
        """
        return self._parsed_requirement[0]

    @property
    def extra(self):
        """
        Get the extras from the requirement
        """
        return self._parsed_requirement[1]

    @property
    def version_evals(self):
        """
        Return the version evaluations for the requirement if present
        """
        if not self._parsed_requirement[2]:
            return []
        return self._parsed_requirement[2]

    @property
    def env_evals(self):
        """
        Return any environment evaluations for the requirement
        """
        if not self._parsed_requirement[3]:
            return []
        return self._parsed_requirement[3]

    @property
    def env_matches(self):
        """
        Determine if the current env matches the requirement

        Returns
        -------
        True if it matches
        """
        env_evals = list(self.env_evals)
        env_evals = self.evaluate_matches(env_evals)
        if len(env_evals) == 3:
            env_evals = [self.evaluate(*env_evals)]
        return False not in env_evals

    def evaluate_matches(self, env_evals):
        """
        Evaluate all of the statements and return a list of the results
        Parameters
        ----------
        env_evals: evals to be evaluated

        Returns
        -------
        Evaluates all the statements and return the ones that match
        """
        for element_num in range(len(env_evals)):  # pylint: disable=consider-using-enumerate
            entry = env_evals[element_num]
            if isinstance(entry, str):
                continue
            operation, val1, val2 = entry
            env_evals[element_num] = self.evaluate(operation, val1, val2)
        return env_evals

    def evaluate(self, operation, val1, val2):
        """Evaluate"""
        if isinstance(val1, tuple):
            val1 = self.evaluate(*val1)
        if isinstance(val2, tuple):
            val2 = self.evaluate(*val2)

        if isinstance(val1, str):
            val1 = pkg_resources.parse_version(val1)
        if isinstance(val2, str):
            val2 = pkg_resources.parse_version(val2)

        # statement = f'{val1} {operation} {val2}'

        result = None
        if operation == '>':
            result = val1 > val2
        elif operation == '<':
            result = val1 < val2
        elif operation == '>=':
            result = val1 >= val2
        elif operation == '<=':
            result = val1 <= val2
        elif operation == '==':
            result = val1 == val2
        elif operation in ['!', '!=']:
            result = val1 != val2
        elif operation == 'and':
            result = val1 and val2
        elif operation == 'or':
            result = val1 or val2
        else:
            logger.error(f'Invalid operation {operation}')
        # logger.debug(f'Evaluated {statement} == {result}')
        return result
Beispiel #33
0
 def get_distro_id_base():
     """
         Returns a compatible distro id.
     """
     return distro.like() or distro.id()
Beispiel #34
0
#####################################################################


if __name__ == "__main__":
    # # Configurable installation roots for various data files.

    # Trailing slashes on these vars is to allow for easy
    # later configuration of relative paths if desired.
    docpath = "share/man/man1"
    etcpath = "/etc/cobbler/"
    initpath = "/etc/init.d/"
    libpath = "/var/lib/cobbler/"
    logpath = "/var/log/"
    statepath = "/tmp/cobbler_settings/devinstall"
    httpd_service = "httpd.service"
    suse_release = "suse" in distro.like()

    if suse_release:
        webconfig = "/etc/apache2/conf.d"
        webroot = "/srv/www/"
        http_user = "******"
        httpd_service = "apache2.service"
        defaultpath = "/etc/sysconfig/"
    elif os.path.exists("/etc/debian_version"):
        if os.path.exists("/etc/apache2/conf-available"):
            webconfig = "/etc/apache2/conf-available"
        else:
            webconfig = "/etc/apache2/conf.d"
        webroot = "/srv/www/"
        http_user = "******"
        defaultpath = "/etc/default/"