コード例 #1
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')
コード例 #2
0
ファイル: install.py プロジェクト: gigaSproule/dotfiles
def get_system():
    if sys.platform == 'linux':
        install_required_dependencies('distro')
        import distro
        if distro.name() == 'Ubuntu':
            current_desktop = os.environ['XDG_CURRENT_DESKTOP']
            if current_desktop == 'KDE':
                print('Detected Kubuntu')
                return Kubuntu()
            elif current_desktop == 'LXQt' or current_desktop == 'LXDE':
                print('Detected Lubuntu')
                return Lubuntu()
            elif current_desktop == 'XFCE':
                print('Detected Xubuntu')
                return Xubuntu()
            else:
                print('Detected Ubuntu')
                return Ubuntu()
        elif distro.name() == 'Arch Linux':
            print('Detected Arch')
            return Arch()
        else:
            return Linux()
    elif sys.platform == 'darwin':
        print('Detected Mac')
        return Mac()
    elif sys.platform == 'win32' or sys.platform == 'cygwin':
        print('Detected Windows')
        return Windows()
    else:
        EnvironmentError('Unknown operating system')
コード例 #3
0
ファイル: AgentInfo.py プロジェクト: moutainhigh/xdcs
    def GetSystemInfo(self, request, context) -> SystemInfo:
        system_info = SystemInfo()

        system_info.python_version.major = sys.version_info.major
        system_info.python_version.minor = sys.version_info.minor
        system_info.python_version.micro = sys.version_info.micro
        system_info.python_version.releaselevel = sys.version_info.releaselevel
        system_info.python_version.serial = sys.version_info.serial
        system_info.python_version.version_str = sys.version

        system_info.system_family = os.name
        system_info.system_family_name = platform.system()
        system_info.platform = platform.platform()
        for name, value in os.environ.items():
            system_info.env[name] = value
        system_info.uname_sysname = platform.system()
        system_info.uname_nodename = platform.node()
        system_info.uname_release = platform.release()
        system_info.uname_version = platform.version()
        system_info.uname_machine = platform.machine()
        system_info.dist_name = distro.name()
        system_info.dist_desc = distro.name(True)
        system_info.dist_version = distro.version()
        system_info.dist_id = distro.id()

        return system_info
コード例 #4
0
ファイル: end2end_test.py プロジェクト: nondejus/ddisasm
def compatible_test(config, test):
    # Check the test case is compatible with this platform.
    if "platform" in config:
        if platform.system() not in config["platform"]:
            return False

    # Check the test case is compatible with this distro.
    if "distro" in config:
        if distro.name() not in config["distro"]["name"]:
            return False
        if distro.version() not in config["distro"]["version"]:
            return False

    # Individual test can also be deactivated for a distro

    # Check the test case is compatible with this platform.
    if "platform" in test:
        if platform.system() not in test["platform"]:
            return False

    # Check the test case is compatible with this distro.
    if "distro" in test:
        if distro.name() not in test["distro"]["name"]:
            return False
        if distro.version() not in test["distro"]["version"]:
            return False

    return True
コード例 #5
0
ファイル: end2end_test.py プロジェクト: GrammaTech/ddisasm
def compatible_test(config, test):
    # Check the test case is compatible with this platform.
    if "platform" in config:
        if platform.system() not in config["platform"]:
            return False

    # Check the test case is compatible with this distro.
    if "distro" in config:
        if distro.name() not in config["distro"]["name"]:
            return False
        if distro.version() not in config["distro"]["version"]:
            return False

    # Individual test can also be deactivated for a distro

    # Check the test case is compatible with this platform.
    if "platform" in test:
        if platform.system() not in test["platform"]:
            return False

    # Check the test case is compatible with this distro.
    if "distro" in test:
        if distro.name() not in test["distro"]["name"]:
            return False
        if distro.version() not in test["distro"]["version"]:
            return False

    # TODO: Can we have a hybrid x86_32 and x86_64 vcvar environment?
    if "platform" in config and "arch" in test:
        if "Windows" in config["platform"]:
            if os.environ["VSCMD_ARG_TGT_ARCH"] != test["arch"]:
                return False
    return True
コード例 #6
0
ファイル: test_local_project.py プロジェクト: packit/packit
class TestLocalProject(PackitTest):
    """Test LocalProject and save interaction with GitHub"""
    def cassette_setup(self, cassette):
        """requre requires this method to be present"""
        cassette.data_miner.data_type = DataTypes.Dict

    @staticmethod
    def commit_title(lp: LocalProject):
        commit_msg = lp.git_repo.head.commit.message
        return commit_msg.split("\n", 1)[0]

    @pytest.mark.skipif(
        distro.name() == "CentOS Stream" and distro.version() == "8",
        reason=
        "This test is know to fail on el8: https://github.com/packit/requre/issues/233",
    )
    def test_checkout_pr(self):
        """Test PR checkout with and without merging"""
        project = LocalProject(
            git_project=self.project,
            pr_id=PR_ID,
            git_url=self._project_url,
            working_dir=self.static_tmp,
        )
        assert project.ref == f"pr/{PR_ID}"
        # check that HEAD of the merge matches HEAD of main
        main = project.git_repo.heads["main"]
        # 'Merge pull request #231 from packit/pre-commit-ci-update-config
        assert self.commit_title(project) == main.commit.message.split(
            "\n", 1)[0]
        assert "koji_build" in (project.working_dir /
                                ".packit.yaml").read_text()

    @pytest.mark.skipif(
        distro.name() == "CentOS Stream" and distro.version() == "8",
        reason=
        "This test is know to fail on el8: https://github.com/packit/requre/issues/233",
    )
    def test_checkout_pr_no_merge(self):
        """Test PR checkout with and without merging"""
        project = LocalProject(
            git_project=self.project,
            pr_id=PR_ID,
            git_url=self._project_url,
            working_dir=self.static_tmp,
            merge_pr=False,
        )
        assert project.ref == f"pr/{PR_ID}"
        assert (self.commit_title(project) ==
                "Run Koji builds automatically for new dist-git commits")
        assert "koji_build" in (project.working_dir /
                                ".packit.yaml").read_text()
コード例 #7
0
def get_distro(remote=False, ip=None):
    """ Get os distribution, version, and architecture

    :param remote:
    :param ip:
    :return: tuple: os distribution, version, and architecture
    """
    if remote:
        host_info = {}
        while len(host_info) == 0:
            host_info = get_os_type(ip)
        return host_info['NAME'].strip('"'), \
            host_info['VERSION_ID'].strip('"'), None
    else:
        os = platform.platform()
        if "Linux" in os:
            # Workaround for lsb_release returning "n/a" in MSVSphere 6.3
            if distro.name(True) == "MSVSphere 6.3":
                return "\xd0\x9c\xd0\xa1\xd0\x92\xd0\xa1\xd1\x84\xd0\xb5" \
                    "\xd1\x80\xd0\xb0 \xd0\xa1\xd0\xb5\xd1\x80\xd0\xb2" \
                    "\xd0\xb5\xd1\x80", \
                    "6.3", \
                    platform.machine()
            return distro.linux_distribution()[0].strip('"'), \
                distro.linux_distribution()[1], \
                platform.machine()
        elif "Windows" in os:
            return 'Windows-' + platform.win32_ver()[0], \
                '.'.join(platform.win32_ver()[1].split('.')[:-1]), \
                platform.machine()
        else:
            raise Exception("Unknown OS platform (%s)." % os)
コード例 #8
0
ファイル: util.py プロジェクト: pyinmana/system76-driver
def dump_logs(base):
    fp = open(path.join(base, 'systeminfo.txt'), 'x')
    fp.write('System76 Model: {}\n'.format(determine_model()))
    fp.write('OS Version: {}\n'.format(', '.join(distro.name())))
    fp.write('Kernel Version: {}\n'.format(distro.os.uname().release))

    fp = open(path.join(base, 'dmidecode'), 'xb')
    SubProcess.check_call(['dmidecode'], stdout=fp)

    fp = open(path.join(base, 'lspci'), 'xb')
    SubProcess.check_call(['lspci', '-vv'], stdout=fp)

    fp = open(path.join(base, 'lsusb'), 'xb')
    SubProcess.check_call(['lsusb', '-vv'], stdout=fp)

    fp = open(path.join(base, 'dmesg'), 'xb')
    SubProcess.check_call(['dmesg'], stdout=fp)

    fp = open(path.join(base, 'journalctl'), 'xb')
    SubProcess.check_call(['journalctl', '--since', 'yesterday'], stdout=fp)

    for parts in [('Xorg.0.log',), ('syslog',)]:  #, ('apt', 'history.log')]:
        src = path.join('/var/log', *parts)
        if path.isfile(src):
            dst = path.join(base, *parts)
            dst_dir = path.dirname(dst)
            if not path.isdir(dst_dir):
                os.makedirs(dst_dir)
            assert not path.exists(dst)
            shutil.copy(src, dst)
コード例 #9
0
def print_system_info():
    print("If you do not understand why the above failures occurred,")
    print("copy and send the *entire* output (all info above and summary")
    print("below) to the instructor for help.")
    print()
    print('==================')
    print('System information')
    print('==================')
    _print_info('os.name', _os.name)
    _print_info('os.uname', _platform.uname())
    _print_info('platform', _sys.platform)
    _print_info('platform+', _platform.platform())
    system = _platform.system()
    if system == 'Linux' and _distro:
        _print_info('linux_distribution',
                    _distro.name(pretty=True) or _distro.linux_distribution())
    else:
        for pversion in (
                'linux_distribution',
                'mac_ver',
                'win32_ver',
        ):
            value = getattr(_platform, pversion)()
            if value[0]:
                _print_info(pversion, value)
    _print_info('prefix', _sys.prefix)
    _print_info('exec_prefix', _sys.exec_prefix)
    _print_info('executable', _sys.executable)
    _print_info('version_info', _sys.version_info)
    _print_info('version', _sys.version)
    _print_info('environment', '')
    for key, value in sorted(_os.environ.items()):
        print('  {0}={1}'.format(key, value))
    print('==================')
コード例 #10
0
ファイル: system_info.py プロジェクト: keanuplayz/dotfiles
def _get_distro_info() -> Tuple[str, str, str, str]:
    if psutil.WINDOWS:
        return "windows", platform.system(), platform.release(), ""
    elif psutil.OSX:
        import plistlib

        with open("/System/Library/CoreServices/SystemVersion.plist",
                  "rb") as f:
            sw_vers = plistlib.load(f)
        return "mac", sw_vers["ProductName"], sw_vers["ProductVersion"], ""
    elif _is_android():
        import subprocess

        android_version = subprocess.run(
            ["getprop", "ro.build.version.release"],
            check=True,
            stdout=subprocess.PIPE,
        ).stdout
        return "android", "Android", android_version.decode().strip(), ""
    elif psutil.LINUX:
        import distro

        return distro.id(), distro.name(), distro.version(), distro.codename()

    raise NotImplementedError("unsupported OS")
コード例 #11
0
 def __init__(self):
     try:
         self.name = distro.name()
         self.version = distro.version()
     except NameError:
         self.name = platform.dist()[0]
         self.version = platform.dist()[1]
コード例 #12
0
def get_background_cmd(photo_name: str):
    system = platform.system()
    if system == 'Darwin':
        raise ValueError(
            'macOS is not yet implemented to change the background. However, you can still change the background. photo name: {}'.format(
                photo_name))
    elif system == 'Linux':
        logging.info('Linux OS found; finding distro')
        dist = distro.name()
        logging.info('Found {}'.format(dist))
        if 'elementary' in dist or 'Ubuntu' in dist:
            return [
                'gsettings',
                'set',
                'org.gnome.desktop.background',
                'picture-uri',
                'file://' + photo_name
            ]
    elif system == 'Windows':
        raise ValueError(
            'Windows is not yet implemented to change the background. However, you can still change the background. photo name: {}'.format(
                photo_name))
    raise ValueError(
        '{} is not yet implemented to change the background. However, you can still change the background. photo name: {}'.format(
            system, photo_name))
コード例 #13
0
def platform_info():
    machine = platform.machine()
    processor = platform.processor()
    system = platform.system()

    cpuinfo_f = '/proc/cpuinfo'

    if (processor in {machine, 'unknown'} and os.path.exists(cpuinfo_f)):
        with open(cpuinfo_f, 'rt') as f:
            for line in f:
                if line.startswith('model name'):
                    _, _, p = line.partition(':')
                    processor = p.strip()
                    break

    if 'Linux' in system:
        distribution = '{} {}'.format(distro.name(), distro.version()).strip()
    else:
        distribution = None

    data = {
        'cpu': processor,
        'arch': machine,
        'system': '{} {}'.format(system, platform.release()),
        'distribution': distribution
    }

    return data
コード例 #14
0
    def __init__(self, config: ConfigHelper) -> None:
        self.server = config.get_server()
        dist_info: Dict[str, Any]
        dist_info = {'name': distro.name(pretty=True)}
        dist_info.update(distro.info())
        dist_info['release_info'] = distro.distro_release_info()
        self.inside_container = False
        self.system_info: Dict[str, Any] = {
            'python': {
                "version": sys.version_info,
                "version_string": sys.version.replace("\n", " ")
            },
            'cpu_info': self._get_cpu_info(),
            'sd_info': self._get_sdcard_info(),
            'distribution': dist_info,
            'virtualization': self._check_inside_container()
        }
        self._update_log_rollover(log=True)
        providers: Dict[str, type] = {
            "none": BaseProvider,
            "systemd_cli": SystemdCliProvider,
            "systemd_dbus": SystemdDbusProvider
        }
        ptype = config.get('provider', 'systemd_dbus')
        pclass = providers.get(ptype)
        if pclass is None:
            raise config.error(f"Invalid Provider: {ptype}")
        self.sys_provider: BaseProvider = pclass(config)
        logging.info(f"Using System Provider: {ptype}")

        self.server.register_endpoint("/machine/reboot", ['POST'],
                                      self._handle_machine_request)
        self.server.register_endpoint("/machine/shutdown", ['POST'],
                                      self._handle_machine_request)
        self.server.register_endpoint("/machine/services/restart", ['POST'],
                                      self._handle_service_request)
        self.server.register_endpoint("/machine/services/stop", ['POST'],
                                      self._handle_service_request)
        self.server.register_endpoint("/machine/services/start", ['POST'],
                                      self._handle_service_request)
        self.server.register_endpoint("/machine/system_info", ['GET'],
                                      self._handle_sysinfo_request)

        self.server.register_notification("machine:service_state_changed")

        # Register remote methods
        self.server.register_remote_method("shutdown_machine",
                                           self.sys_provider.shutdown)
        self.server.register_remote_method("reboot_machine",
                                           self.sys_provider.reboot)

        # IP network shell commands
        shell_cmd: SCMDComp = self.server.load_component(
            config, 'shell_command')
        self.addr_cmd = shell_cmd.build_shell_command("ip -json address")
        iwgetbin = "/sbin/iwgetid"
        if not pathlib.Path(iwgetbin).exists():
            iwgetbin = "iwgetid"
        self.iwgetid_cmd = shell_cmd.build_shell_command(iwgetbin)
        self.init_evt = asyncio.Event()
コード例 #15
0
ファイル: puddletag.py プロジェクト: puddletag/puddletag
    def get_linux_name():
        """Returns the name of the linux distribution. Hopefully."""
        # First try: The optional distro package (should always work if available)
        try:
            import distro
        except ImportError:
            pass
        else:
            return distro.name(True)

        # Second try: the new function in platform (py v3.10+ only)
        if hasattr(platform, 'freedesktop_os_release'):
            try:
                return osrelease_dict_to_str(platform.freedesktop_os_release())
            except OSError:
                pass

        # Third try: the old function in platform (until py v3.7 only)
        if hasattr(platform, 'linux_distribution'):
            linux_dist = platform.linux_distribution()
            if any((x for x in linux_dist if x)):
                return '%s %s' % (linux_dist[0], linux_dist[1])

        # Fourth try: read the os-release file directly (to fill the gap btw. 3.7 and 3.10)
        try:
            return osrelease_dict_to_str(read_osrelease())
        except OSError:
            pass

        # We tried hard, but it wasn't enough.
        return None
コード例 #16
0
def main():

    dist_name = distro.name().lower()

    if dist_name in [
            'ubuntu', 'debian', 'kali', 'debian gnu/linux', 'kali gnu/linux'
    ]:
        debian()

    elif dist_name == 'fedora':
        fedora()

    elif dist_name in [
            'archlinux', 'arch', 'arch linux', 'manjaro', 'manjaro linux'
    ]:
        archlinux()

    elif dist_name == 'parrot gnu/linux':
        parrot()

    else:
        logger.error(
            'Unhandled distribution to install deps: {}'.format(dist_name))
        logger.error('Please poke me or submit a PR.')
        return
コード例 #17
0
    def __no_qt_package_error(self):
        import distro
        cpu_architecture = platform.machine()

        print('')
        hifi_utils.color('red')
        print("Sorry, we don't have a prebuilt Qt package for " +
              distro.name(pretty=True) + " on " + cpu_architecture + ".")
        hifi_utils.color('white')
        print('')
        print(
            "If this is a recent distribution, dating from 2021 or so, you can try building"
        )
        print(
            "against the system Qt by running this command, and trying again:")
        print("    export VIRCADIA_USE_SYSTEM_QT=1")
        print("")
        hifi_utils.color('clear')
        print(
            "If you'd like to try to build Qt from source either for building Vircadia, or"
        )
        print(
            "to contribute a prebuilt package for your distribution, please see the"
        )
        print("documentation at: ", end='')
        hifi_utils.color('blue')
        print(
            "https://github.com/vircadia/vircadia/tree/master/tools/qt-builder"
        )
        hifi_utils.color('clear')
        print('')
        raise hifi_utils.SilentFatalError(2)
コード例 #18
0
def set_distro():
    os = sys.platform
    if os == 'darwin':
        return 'darwin'
    elif os.startswith('linux'):
        try:
            import distro
            dist = distro.id()
            name = distro.name()
        except ImportError:
            dist = 'ubuntu' # default value, will remove DISTRO
            name = 'Ubuntu' # in future.
        # To add new distributions, refer to:
        #    http://distro.readthedocs.io/en/latest/#distro.id
        #    http://linuxmafia.com/faq/Admin/release-files.html
        if dist in ('ubuntu', 'debian'):
            return 'debian'
        elif dist in ('fedora', 'rhel', 'centos'):
            return 'fedora'
        elif dist == 'arch':
            return 'arch'
        else:
            raise ValueError(
                "Not supported for your Linux distribution: {}"\
                .format(name)
            )
    else:
        raise ValueError(
            "Not supported for your OS: {}"\
            .format(os)
        )
コード例 #19
0
    def __init__(self, config):
        self.server = config.get_server()
        dist_info = {'name': distro.name(pretty=True)}
        dist_info.update(distro.info())
        self.system_info = {
            'cpu_info': self._get_cpu_info(),
            'sd_info': self._get_sdcard_info(),
            'distribution': dist_info
        }
        # Add system info to log rollover
        sys_info_msg = "\nSystem Info:"
        for header, info in self.system_info.items():
            sys_info_msg += f"\n\n***{header}***"
            for key, val in info.items():
                sys_info_msg += f"\n  {key}: {val}"
        self.server.add_log_rollover_item('system_info', sys_info_msg)

        self.server.register_endpoint("/machine/reboot", ['POST'],
                                      self._handle_machine_request)
        self.server.register_endpoint("/machine/shutdown", ['POST'],
                                      self._handle_machine_request)
        self.server.register_endpoint("/machine/services/restart", ['POST'],
                                      self._handle_service_request)
        self.server.register_endpoint("/machine/services/stop", ['POST'],
                                      self._handle_service_request)
        self.server.register_endpoint("/machine/services/start", ['POST'],
                                      self._handle_service_request)
        self.server.register_endpoint("/machine/system_info", ['GET'],
                                      self._handle_sysinfo_request)

        # Register remote methods
        self.server.register_remote_method("shutdown_machine",
                                           self.shutdown_machine)
        self.server.register_remote_method("reboot_machine",
                                           self.reboot_machine)
コード例 #20
0
def get_os_name():
    """
    Determine system name, e.g., 'redhat' (generic), 'centos', 'debian', 'fedora', 'suse', 'ubuntu',
    'red hat enterprise linux server', 'SL' (Scientific Linux), 'opensuse', ...
    """
    os_name = None

    # platform.linux_distribution was removed in Python 3.8,
    # see https://docs.python.org/2/library/platform.html#platform.linux_distribution
    if hasattr(platform, 'linux_distribution'):
        # platform.linux_distribution is more useful, but only available since Python 2.6
        # this allows to differentiate between Fedora, CentOS, RHEL and Scientific Linux (Rocks is just CentOS)
        os_name = platform.linux_distribution()[0].strip().lower()
    elif HAVE_DISTRO:
        # distro package is the recommended alternative to platform.linux_distribution,
        # see https://pypi.org/project/distro
        os_name = distro.name()
    else:
        # no easy way to determine name of Linux distribution
        os_name = None

    os_name_map = {
        'red hat enterprise linux server': 'RHEL',
        'red hat enterprise linux': 'RHEL',  # RHEL8 has no server/client
        'scientific linux sl': 'SL',
        'scientific linux': 'SL',
        'suse linux enterprise server': 'SLES',
    }

    if os_name:
        return os_name_map.get(os_name, os_name)
    else:
        return UNKNOWN
コード例 #21
0
ファイル: asm_db.py プロジェクト: jeshan/ddisasm
def upload(name, asm, compilers, compiler_args, strip):
    conn = DB()
    if conn:
        cursor = conn.cursor()

        # Upsert assembly contents to the `assembly' table.
        with open(asm, "r") as f:
            contents = f.read()
            checksum = hashlib.md5(contents.encode("utf-8")).hexdigest()
            cursor.execute(
                """
                INSERT INTO assembly (checksum, content)
                VALUES (%s, %s)
                ON CONFLICT (checksum)
                DO UPDATE SET updated_at = NOW()
                RETURNING assembly_id
            """,
                (checksum, contents),
            )
            assembly_id = cursor.fetchone()[0]

        # Insert disassembly details into the `disassembled' table.
        cursor.execute(
            """
            INSERT INTO disassembled (
                name,
                assembly_id,
                compiler,
                compiler_args,
                platform,
                distro,
                ci_job_image,
                ci_pipeline_id,
                ci_commit_sha,
                ci_commit_before_sha,
                ci_commit_branch,
                ci_commit_ref_slug,
                strip
            )
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        """,
            (
                name,
                assembly_id,
                " ".join(compilers),
                " ".join(compiler_args),
                platform.system(),
                " ".join([distro.name(), distro.version()]),
                os.environ.get("CI_JOB_IMAGE"),
                os.environ.get("CI_PIPELINE_ID"),
                os.environ.get("CI_COMMIT_SHA"),
                os.environ.get("CI_COMMIT_BEFORE_SHA"),
                os.environ.get("CI_COMMIT_BRANCH"),
                os.environ.get("CI_COMMIT_REF_SLUG"),
                strip,
            ),
        )

        conn.commit()
コード例 #22
0
ファイル: systemOptions.py プロジェクト: Laburda/Jarvis-3
def Os__LINUX(jarvis, s):
    """Displays information about your operating system"""
    jarvis.say('[!] Operating System Information', Fore.BLUE)
    jarvis.say('[*] ' + sys(), Fore.GREEN)
    jarvis.say('[*] ' + release(), Fore.GREEN)
    jarvis.say('[*] ' + distro.name(), Fore.GREEN)
    for _ in architecture():
        jarvis.say('[*] ' + _, Fore.GREEN)
コード例 #23
0
ファイル: utils.py プロジェクト: rstollander/migasfree-client
def get_distro_name():
    try:
        import distro

        name = distro.name()
    except ImportError:
        name = platform.linux_distribution()[0]

    return slugify(name.strip().split()[0])
コード例 #24
0
ファイル: report_to_loki.py プロジェクト: leuc/cozy
def report(component: str, type: LogLevel, message: str, exception: Exception):
    if ENABLE != 'true':
        return

    app_settings = inject.instance(ApplicationSettings)
    report_level = app_settings.report_level

    if report_level == 0:
        return

    curr_datetime = datetime.datetime.now(pytz.timezone('Europe/Berlin'))
    curr_datetime = curr_datetime.isoformat('T')

    if not component or not type or not message:
        raise ValueError("component, type and message are mandatory")

    labels = __append_label("", "component", component)

    if exception:
        labels = __append_label(labels, "exception_type",
                                exception.__class__.__name__)

    labels = __append_label(labels, "app", "cozy")
    labels = __append_label(labels, "level", LOG_LEVEL_MAP[type])

    labels = __append_label(
        labels, "gtk_version", "{}.{}".format(Gtk.get_major_version(),
                                              Gtk.get_minor_version()))
    labels = __append_label(labels, "python_version",
                            platform.python_version())
    labels = __append_label(labels, "peewee_version", PeeweeVersion)
    labels = __append_label(labels, "mutagen_version", MutagenVersion)
    labels = __append_label(labels, "apsw_version", APSWVersion())
    labels = __append_label(labels, "version", CozyVersion)

    if report_level > 1:
        labels = __append_label(labels, "distro", distro.name())
        labels = __append_label(labels, "distro_version", distro.version())
        labels = __append_label(labels, "desktop_environment",
                                os.environ.get('DESKTOP_SESSION'))

    line = "[{}] {}".format(LOG_LEVEL_MAP[type], message)

    headers = {'Content-type': 'application/json'}
    payload = {
        'streams': [{
            'labels': "{{{}}}".format(labels),
            'entries': [{
                'ts': curr_datetime,
                'line': line
            }]
        }]
    }
    try:
        requests.post(URL, json=payload, headers=headers, timeout=10)
    except:
        pass
コード例 #25
0
ファイル: utils.py プロジェクト: migasfree/migasfree-client
def get_distro_project():
    try:
        import distro

        project = '{0}-{1}'.format(distro.name(), distro.version())
    except ImportError:
        project = '-'.join(platform.linux_distribution()[0:2])

    return slugify(project)
コード例 #26
0
ファイル: utils.py プロジェクト: migasfree/migasfree-client
def get_distro_name():
    try:
        import distro

        name = distro.name()
    except ImportError:
        name = platform.linux_distribution()[0]

    return slugify(name.strip().split()[0])
コード例 #27
0
ファイル: utils.py プロジェクト: rstollander/migasfree-client
def get_distro_project():
    try:
        import distro

        project = '{0}-{1}'.format(distro.name(), distro.version())
    except ImportError:
        project = '-'.join(platform.linux_distribution()[0:2])

    return slugify(project)
コード例 #28
0
ファイル: facts.py プロジェクト: ryan-blakley/pbr
    def __init__(self):
        """
        The facts class is meant to determine different facts about the server being
        backed up, like what the storage layout is, what are the mount points, selinux,
        etc. The variables are used through out the application for various stuff.
        """
        self.lvm = dict()

        # Some of these need to be called in order.
        self.recovery_mode = environ.get('RECOVERY_MODE', False)
        self.hostname = uname().nodename
        self.distro = distro.name()
        self.distro_pretty = distro.name(pretty=True)
        self.uname = uname().release
        self.udev_ctx = Context()
        self.mnts = get_mnts(self.udev_ctx)
        self.disks = get_part_layout(self.udev_ctx)
        self.lvm_installed = rpmq("lvm2")

        if not self.recovery_mode:
            self.modules = get_modules()
            self.uefi = exists("/sys/firmware/efi")
            self.arch = machine()

            from selinux import is_selinux_enabled, security_getenforce
            if is_selinux_enabled():
                self.selinux_enabled = 1
                self.selinux_enforcing = security_getenforce()
            else:
                self.selinux_enabled = 0
                self.selinux_enforcing = 0

            if rpmq("mokutil") and "enabled" in run_cmd(
                ['mokutil', '--sb-state'], ret=True).stdout.decode():
                self.secure_boot = 1
            else:
                self.secure_boot = 0

        # Confirm the lvm2 pkg is installed before querying lvm.
        if self.lvm_installed:
            self.lvm = get_lvm_report(self.udev_ctx)

        self.md_info = get_md_info(self.udev_ctx)
        self.luks = get_luks_devs(self.udev_ctx)
コード例 #29
0
def get_os_distribution():
    try:
        return platform.dist()
    except Exception:
        import distro
        return [
            distro.name(),
            distro.major_version() + '.' + distro.minor_version(),
            distro.codename()
        ]
コード例 #30
0
ファイル: gtkexcepthook.py プロジェクト: Hoeze/gajim
def get_os_info():
    if os.name == 'nt' or sys.platform == 'darwin':
        return platform.system() + " " + platform.release()
    elif os.name == 'posix':
        try:
            import distro
            return distro.name(pretty=True)
        except ImportError:
            return platform.system()
    return ''
コード例 #31
0
ファイル: utils.py プロジェクト: lino-framework/getlino
 def __init__(self, batch=False):
     self.batch = batch
     # self.asroot = ifroot()
     self._services = set()
     self._system_packages = set()
     if ifroot():
         click.echo("Running as root.")
     click.echo("This is getlino version {} running on {} ({} {}).".format(
         SETUP_INFO['version'], distro.name(pretty=True), distro.id(),
         distro.codename()))
コード例 #32
0
def get_python_os_info(pretty: bool = False) -> Tuple[str, str]:
    """
    Get Operating System type/distribution and major version
    using python platform module

    :param bool pretty: If the returned OS name should be in longer (pretty) form

    :returns: (os_name, os_version)
    :rtype: `tuple` of `str`
    """
    info = platform.system_alias(platform.system(), platform.release(),
                                 platform.version())
    os_type, os_ver, _ = info
    os_type = os_type.lower()
    if os_type.startswith('linux') and _USE_DISTRO:
        distro_name, distro_version = distro.name() if pretty else distro.id(
        ), distro.version()
        # On arch, these values are reportedly empty strings so handle it
        # defensively
        # so handle it defensively
        if distro_name:
            os_type = distro_name
        if distro_version:
            os_ver = distro_version
    elif os_type.startswith('darwin'):
        try:
            proc = subprocess.run(
                ["/usr/bin/sw_vers", "-productVersion"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                check=False,
                universal_newlines=True,
                env=env_no_snap_for_external_calls(),
            )
        except OSError:
            proc = subprocess.run(
                ["sw_vers", "-productVersion"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                check=False,
                universal_newlines=True,
                env=env_no_snap_for_external_calls(),
            )
        os_ver = proc.stdout.rstrip('\n')
    elif os_type.startswith('freebsd'):
        # eg "9.3-RC3-p1"
        os_ver = os_ver.partition("-")[0]
        os_ver = os_ver.partition(".")[0]
    elif platform.win32_ver()[1]:
        os_ver = platform.win32_ver()[1]
    else:
        # Cases known to fall here: Cygwin python
        os_ver = ''
    return os_type, os_ver
コード例 #33
0
ファイル: footer.py プロジェクト: oaubert/python-vlc
 def print_python():
     from platform import architecture, mac_ver, uname, win32_ver
     if 'intelpython' in sys.executable:
         t = 'Intel-'
     # elif 'PyPy ' in sys.version:
     #     t = 'PyPy-'
     else:
         t = ''
     t = '%sPython: %s (%s)' % (t, sys.version.split()[0], architecture()[0])
     if win32_ver()[0]:
         t = t, 'Windows', win32_ver()[0]
     elif mac_ver()[0]:
         t = t, ('iOS' if sys.platform == 'ios' else 'macOS'), mac_ver()[0]
     else:
         try:
             import distro  # <http://GitHub.com/nir0s/distro>
             t = t, bytes_to_str(distro.name()), bytes_to_str(distro.version())
         except ImportError:
             t = (t,) + uname()[0:3:2]
     print(' '.join(t))
コード例 #34
0
ファイル: depends.py プロジェクト: openstack-infra/bindep
    def platform_profiles(self):
        if platform.system() == 'Darwin':
            atoms = set(['darwin'])
            # detect available macos package managers
            if os.system('which brew >/dev/null') == 0:
                atoms.add('brew')
                self.platform = Brew()
            return ["platform:%s" % (atom,) for atom in sorted(atoms)]
        distro_id = distro.id()
        if not distro_id:
            log = logging.getLogger(__name__)
            log.error('Unable to determine distro ID. '
                      'Does /etc/os-release exist or '
                      'is lsb_release installed?')
            raise Exception('Distro name not found')
        # NOTE(toabctl): distro can be more than one string (i.e. "SUSE LINUX")
        codename = distro.codename().lower()
        release = distro.version().lower()
        # NOTE(toabctl): space is a delimiter for bindep, so remove the spaces
        distro_id = "".join(distro_id.split()).lower()
        atoms = set([distro_id])
        atoms.update(self.codenamebits(distro_id, codename))
        atoms.update(self.releasebits(distro_id, release))
        if distro_id in ["debian", "ubuntu"]:
            atoms.add("dpkg")
            self.platform = Dpkg()
        # RPM distros seem to be especially complicated
        elif distro_id in ["amzn", "amazonami",
                           "centos", "rhel",
                           "redhatenterpriseserver",
                           "redhatenterpriseworkstation",
                           "fedora",
                           "opensuseproject", "opensuse", "opensuse-leap",
                           "opensuse-tumbleweed", "sles", "suselinux"]:
            # Distro aliases
            if distro_id in ["redhatenterpriseserver",
                             "redhatenterpriseworkstation"]:
                # just short alias
                atoms.add("rhel")
                atoms.update(self.codenamebits("rhel", codename))
                atoms.update(self.releasebits("rhel", release))
            elif distro_id == 'rhel' and 'server' in distro.name().lower():
                atoms.add("redhatenterpriseserver")
                atoms.update(self.codenamebits("redhatenterpriseserver",
                                               codename))
                atoms.update(self.releasebits("redhatenterpriseserver",
                                              release))
            elif (distro_id == 'rhel' and
                    'workstation' in distro.name().lower()):
                atoms.add("redhatenterpriseworkstation")
                atoms.update(self.codenamebits("redhatenterpriseworkstation",
                                               codename))
                atoms.update(self.releasebits("redhatenterpriseworkstation",
                                              release))
            elif "amzn" in distro_id:
                atoms.add("amazonami")
                atoms.update(self.codenamebits("amazonami", codename))
                atoms.update(self.releasebits("amazonami", release))
            elif "amazonami" in distro_id:
                atoms.add("amzn")
                atoms.update(self.codenamebits("amzn", codename))
                atoms.update(self.releasebits("amzn", release))
            elif "opensuse" in distro_id:
                # just short alias
                atoms.add("opensuse")
                atoms.update(self.codenamebits("opensuse", codename))
                atoms.update(self.releasebits("opensuse", release))
                atoms.add("opensuseproject")
                atoms.update(self.codenamebits("opensuseproject", codename))
                atoms.update(self.releasebits("opensuseproject", release))
            elif "sles" in distro_id:
                atoms.add("suselinux")
                atoms.update(self.codenamebits("suselinux", codename))
                atoms.update(self.releasebits("suselinux", release))
            elif "suselinux" in distro_id:
                atoms.add("sles")
                atoms.update(self.codenamebits("sles", codename))
                atoms.update(self.releasebits("sles", release))

            # Family aliases
            if 'suse' in distro_id or distro_id == 'sles':
                atoms.add("suse")
            else:
                atoms.add("redhat")

            atoms.add("rpm")
            self.platform = Rpm()
        elif distro_id in ["gentoo"]:
            atoms.add("emerge")
            self.platform = Emerge()
        elif distro_id in ["arch"]:
            atoms.add("pacman")
            self.platform = Pacman()
        elif distro_id in ["alpine"]:
            atoms.add("apk")
            self.platform = Apk()
        else:
            self.platform = Unknown()
        return ["platform:%s" % (atom,) for atom in sorted(atoms)]
コード例 #35
0
ファイル: api.py プロジェクト: andrewwyatt/cobbler
    def __init__(self, is_cobblerd=False):
        """
        Constructor
        """

        # FIXME: this should be switchable through some simple system

        self.__dict__ = CobblerAPI.__shared_state
        self.perms_ok = False
        if not CobblerAPI.__has_loaded:

            # NOTE: we do not log all API actions, because
            # a simple CLI invocation may call adds and such
            # to load the config, which would just fill up
            # the logs, so we'll do that logging at CLI
            # level (and remote.py web service level) instead.

            random.seed()
            self.is_cobblerd = is_cobblerd

            try:
                self.logger = clogger.Logger("/var/log/cobbler/cobbler.log")
            except CX:
                # return to CLI/other but perms are not valid
                # perms_ok is False
                return

            # FIXME: conslidate into 1 server instance

            self.selinux_enabled = utils.is_selinux_enabled()
            self.dist = distro.name().lower()
            self.os_version = utils.os_release()

            CobblerAPI.__has_loaded = True

            # load the modules first, or nothing else works...
            module_loader.load_modules()

            self._collection_mgr = collection_manager.CollectionManager(self)
            self.deserialize()

            # import signatures
            try:
                utils.load_signatures(self.settings().signature_path)
            except Exception as e:
                self.log("Failed to load signatures from %s: %s" % (self.settings().signature_path, e))
                return

            self.log("%d breeds and %d OS versions read from the signature file" % (
                len(utils.get_valid_breeds()), len(utils.get_valid_os_versions()))
            )

            self.authn = self.get_module_from_file(
                "authentication",
                "module",
                "authn_configfile"
            )
            self.authz = self.get_module_from_file(
                "authorization",
                "module",
                "authz_allowall"
            )

            # FIXME: pass more loggers around, and also see that those
            # using things via tasks construct their own yumgen/tftpgen
            # versus reusing this one, which has the wrong logger
            # (most likely) for background tasks.

            self.autoinstallgen = autoinstallgen.AutoInstallationGen(self._collection_mgr)
            self.yumgen = yumgen.YumGen(self._collection_mgr)
            self.tftpgen = tftpgen.TFTPGen(self._collection_mgr, logger=self.logger)
            self.power_mgr = power_manager.PowerManager(self, self._collection_mgr)
            self.logger.debug("API handle initialized")
            self.perms_ok = True
コード例 #36
0
#
# 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())
コード例 #37
0
ファイル: settings.py プロジェクト: GNS3/gns3-gui
else:
    PRECONFIGURED_TELNET_CONSOLE_COMMANDS = {'Xterm': 'xterm -T "%d" -e "telnet %h %p"',
                                             'Putty': 'putty -telnet %h %p -title "%d" -sl 2500 -fg SALMON1 -bg BLACK',
                                             'Gnome Terminal': 'gnome-terminal -t "%d" -e "telnet %h %p"',
                                             'Xfce4 Terminal': 'xfce4-terminal --tab -T "%d" -e "telnet %h %p"',
                                             'ROXTerm': 'roxterm -n "%d" --tab -e "telnet %h %p"',
                                             'KDE Konsole': 'konsole --new-tab -p tabtitle="%d" -e "telnet %h %p"',
                                             'SecureCRT': 'SecureCRT /T /N "%d"  /TELNET %h %p',
                                             'Mate Terminal': 'mate-terminal --tab -e "telnet %h %p"  -t "%d"',
                                             'urxvt': 'urxvt -title %d -e telnet %h %p'}

    # default Telnet console command on other systems
    DEFAULT_TELNET_CONSOLE_COMMAND = PRECONFIGURED_TELNET_CONSOLE_COMMANDS["Xterm"]

    if sys.platform.startswith("linux"):
        distro_name = distro.name()
        if distro_name == "Debian" or distro_name == "Ubuntu" or distro_name == "LinuxMint":
            DEFAULT_TELNET_CONSOLE_COMMAND = PRECONFIGURED_TELNET_CONSOLE_COMMANDS["Gnome Terminal"]

# Pre-configured VNC console commands on various OSes
if sys.platform.startswith("win"):
    # Windows
    PRECONFIGURED_VNC_CONSOLE_COMMANDS = {
        'TightVNC (included with GNS3)': 'tvnviewer.exe %h:%p',
        'UltraVNC': r'"{}\uvnc bvba\UltraVNC\vncviewer.exe" %h:%p'.format(program_files)
    }

    # default Windows VNC console command
    DEFAULT_VNC_CONSOLE_COMMAND = PRECONFIGURED_VNC_CONSOLE_COMMANDS['TightVNC (included with GNS3)']

elif sys.platform.startswith("darwin"):