Python platform.linux_distribution() Examples

The following are 30 code examples of platform.linux_distribution(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module platform , or try the search function .
Example #1
Source File: ssm.py    From aegea with Apache License 2.0 10 votes vote down vote up
def ensure_session_manager_plugin():
    session_manager_dir = os.path.join(config.user_config_dir, "bin")
    PATH = os.environ.get("PATH", "") + ":" + session_manager_dir
    if shutil.which("session-manager-plugin", path=PATH):
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    else:
        os.makedirs(session_manager_dir, exist_ok=True)
        target_path = os.path.join(session_manager_dir, "session-manager-plugin")
        if platform.system() == "Darwin":
            download_session_manager_plugin_macos(target_path=target_path)
        elif platform.linux_distribution()[0] == "Ubuntu":
            download_session_manager_plugin_linux(target_path=target_path)
        else:
            download_session_manager_plugin_linux(target_path=target_path, pkg_format="rpm")
        os.chmod(target_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    return shutil.which("session-manager-plugin", path=PATH) 
Example #2
Source File: covermodes.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def thumb(self):
        dist_name, dist_ver, dist_arch = platform.linux_distribution()
        logger.debug(dist_name)
        if dist_name == 'Ubuntu':
            dist_icon = 'ubuntu'
        elif dist_name == 'debian':
            dist_icon = 'debian'
        elif dist_name == 'fedora':
            dist_icon = 'fedora'
        elif dist_name == 'LinuxMint':
            dist_icon = 'linuxmint'
        elif dist_name == 'openSUSE' or dist_name == 'SuSE':
            dist_icon = 'opensuse'
        elif dist_name == 'gentoo':
            dist_icon = 'gentoo'
        else:
            dist_icon = 'unknown'
        try:
            return self.bridge.device.get_image_url(
                'distribution-{}.png'.format(dist_icon))
        except:
            return None 
Example #3
Source File: setup.py    From rpi-vision with MIT License 6 votes vote down vote up
def run(self):
        system = platform.system()
        machine = platform.machine()
        distro = platform.linux_distribution()

        if 'x86' in machine and system == 'Linux' and 'debian' in distro:
            if 'debian' in distro:
                for command in TRAINER_DEBIAN_CUSTOM_COMMANDS:
                    self.RunCustomCommand(command)
        elif 'arm' in machine and system == 'Linux' and 'debian' in distro:
            for command in TRAINER_DEBIAN_CUSTOM_COMMANDS:
                self.RunCustomCommand(command)
        elif system == 'Darwin':
            for command in TRAINER_DARWIN_CUSTOM_COMMANDS:
                self.RunCustomCommand(command)
        else:
            raise NotImplementedError(
                'Unsupported Platform: {}. Supported platforms are Debian-derived Linux and Darwin (OS X)'.format(system)) 
Example #4
Source File: adminset_agent.py    From adminset with GNU General Public License v2.0 6 votes vote down vote up
def asset_info():
    data_info = dict()
    data_info['memory'] = get_mem_total()
    data_info['disk'] = str(get_disk_info())
    cpuinfo = parser_cpu(get_cpu_model())
    cpucore = get_cpu_cores()
    data_info['cpu_num'] = cpucore['logical']
    data_info['cpu_physical'] = cpucore['physical']
    data_info['cpu_model'] = cpuinfo['model name']
    data_info['ip'] = get_ip()
    data_info['sn'] = parser_dmi(get_dmi())['Serial Number']
    data_info['vendor'] = parser_dmi(get_dmi())['Manufacturer']
    data_info['product'] = parser_dmi(get_dmi())['Version']
    data_info['osver'] = platform.linux_distribution()[0] + " " + platform.linux_distribution()[1] + " " + platform.machine()
    data_info['hostname'] = platform.node()
    data_info['token'] = token
    data_info['agent_version'] = AGENT_VERSION
    return json.dumps(data_info) 
Example #5
Source File: mono.py    From cf-mendix-buildpack with Apache License 2.0 6 votes vote down vote up
def _compose_mono_url_path(mono_version):
    distrib_id = platform.linux_distribution()[0].lower()
    if distrib_id != "ubuntu":
        raise Exception(
            "Only Ubuntu is supported at present, requested distribution: {}".format(
                distrib_id
            )
        )
    distrib_codename = platform.linux_distribution()[2].lower()
    if distrib_codename not in ["trusty", "bionic"]:
        raise Exception(
            "Buildpack supports Trusty and Bionic at the moment, requested version: {}".format(
                distrib_codename
            )
        )
    return "/mx-buildpack/mono/{}-mx-{}-{}.tar.gz".format(
        mono_version, distrib_id, distrib_codename
    ) 
Example #6
Source File: report.py    From hawthorne with GNU Lesser General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
    with Mainframe() as mainframe:
      uname = platform.uname()
      with open(settings.LOGGING['handlers']['file']['filename'], 'r') as log:
        traceback = self.tail(log, 100)

      payload = {
          'path': sys.path,
          'version': platform.python_version(),
          'system': {x: uname.__getattribute__(x) for x in uname._fields},
          'distro': '-'.join(platform.linux_distribution()),
          'log': traceback,
          'directory': settings.BASE_DIR
      }
      response = requests.put("https://{}/api/v1/instance/{}/report".format(
                              settings.MAINFRAME, mainframe().id),
                              json=payload)

      identifier = response.json()['result']['id']

      self.stdout.write(self.style.SUCCESS("""
        When talking to the maintainer indietyp,
        please use this ID to identify your ticket:"""))
      self.stdout.write(identifier) 
Example #7
Source File: software.py    From AstroBox with GNU Affero General Public License v3.0 6 votes vote down vote up
def systemInfo(self):
		distName, distVersion, id = platform.linux_distribution()
		system, node, release, version, machine, processor = platform.uname()

		outdated = distName == 'debian' and distVersion < '8.0'

		return {
			'dist_name': distName,
			'dist_version': distVersion,
			'system': system,
			'release': release,
			'version': version,
			'machine': machine,
			'processor': processor,
			'outdated': outdated
		} 
Example #8
Source File: test_ssl.py    From BinderFilter with MIT License 6 votes vote down vote up
def skip_if_broken_ubuntu_ssl(func):
    if hasattr(ssl, 'PROTOCOL_SSLv2'):
        # We need to access the lower-level wrapper in order to create an
        # implicit SSL context without trying to connect or listen.
        try:
            import _ssl
        except ImportError:
            # The returned function won't get executed, just ignore the error
            pass
        @functools.wraps(func)
        def f(*args, **kwargs):
            try:
                s = socket.socket(socket.AF_INET)
                _ssl.sslwrap(s._sock, 0, None, None,
                             ssl.CERT_NONE, ssl.PROTOCOL_SSLv2, None, None)
            except ssl.SSLError as e:
                if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and
                    platform.linux_distribution() == ('debian', 'squeeze/sid', '')
                    and 'Invalid SSL protocol variant specified' in str(e)):
                    raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour")
            return func(*args, **kwargs)
        return f
    else:
        return func 
Example #9
Source File: gyptest.py    From gyp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_configuration_info():
  print('Test configuration:')
  if sys.platform == 'darwin':
    sys.path.append(os.path.abspath('test/lib'))
    import TestMac
    print('  Mac %s %s' % (platform.mac_ver()[0], platform.mac_ver()[2]))
    print('  Xcode %s' % TestMac.Xcode.Version())
  elif sys.platform == 'win32':
    sys.path.append(os.path.abspath('pylib'))
    import gyp.MSVSVersion
    print('  Win %s %s\n' % platform.win32_ver()[0:2])
    print('  MSVS %s' %
          gyp.MSVSVersion.SelectVisualStudioVersion().Description())
  elif sys.platform in ('linux', 'linux2'):
    print('  Linux %s' % ' '.join(platform.linux_distribution()))
  print('  Python %s' % platform.python_version())
  print('  PYTHONPATH=%s' % os.environ['PYTHONPATH'])
  print() 
Example #10
Source File: test_ssl.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def skip_if_broken_ubuntu_ssl(func):
    if hasattr(ssl, 'PROTOCOL_SSLv2'):
        # We need to access the lower-level wrapper in order to create an
        # implicit SSL context without trying to connect or listen.
        try:
            import _ssl
        except ImportError:
            # The returned function won't get executed, just ignore the error
            pass
        @functools.wraps(func)
        def f(*args, **kwargs):
            try:
                s = socket.socket(socket.AF_INET)
                _ssl.sslwrap(s._sock, 0, None, None,
                             ssl.CERT_NONE, ssl.PROTOCOL_SSLv2, None, None)
            except ssl.SSLError as e:
                if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and
                    platform.linux_distribution() == ('debian', 'squeeze/sid', '')
                    and 'Invalid SSL protocol variant specified' in str(e)):
                    raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour")
            return func(*args, **kwargs)
        return f
    else:
        return func 
Example #11
Source File: gyptest.py    From gyp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def print_configuration_info():
  print('Test configuration:')
  if sys.platform == 'darwin':
    sys.path.append(os.path.abspath('test/lib'))
    import TestMac
    print('  Mac %s %s' % (platform.mac_ver()[0], platform.mac_ver()[2]))
    print('  Xcode %s' % TestMac.Xcode.Version())
  elif sys.platform == 'win32':
    sys.path.append(os.path.abspath('pylib'))
    import gyp.MSVSVersion
    print('  Win %s %s\n' % platform.win32_ver()[0:2])
    print('  MSVS %s' %
          gyp.MSVSVersion.SelectVisualStudioVersion().Description())
  elif sys.platform in ('linux', 'linux2'):
    print('  Linux %s' % ' '.join(platform.linux_distribution()))
  print('  Python %s' % platform.python_version())
  print('  PYTHONPATH=%s' % os.environ['PYTHONPATH'])
  print() 
Example #12
Source File: boxes.py    From saltops with GNU General Public License v3.0 6 votes vote down vote up
def get_items(self):
        upMinionCount = Host.objects.filter(minion_status=1).count()
        downMinionCount = Host.objects.filter(minion_status=0).count()

        # 系统基础信息
        item_info = Item(
            html_id='SysInfo', name='主机系统信息',
            display=Item.AS_TABLE,
            value=(
                ('系统', '%s, %s, %s' % (
                    platform.system(),
                    ' '.join(platform.linux_distribution()),
                    platform.release())),
                ('架构', ' '.join(platform.architecture())),
                ('处理器', platform.processor()),
                ('Python版本', platform.python_version()),
                ('接入主机数量', Host.objects.count()),
                ('业务数量', Project.objects.count()),
                ('客户端运行情况', '运行中 %s,未运行 %s' % (upMinionCount, downMinionCount)),
            ),
            classes='table-bordered table-condensed '
                    'table-hover table-striped'
        )

        return [item_info] 
Example #13
Source File: test_platform.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_linux_distribution_encoding(self):
        # Issue #17429
        with tempfile.TemporaryDirectory() as tempdir:
            filename = os.path.join(tempdir, 'fedora-release')
            with open(filename, 'w', encoding='utf-8') as f:
                f.write('Fedora release 19 (Schr\xf6dinger\u2019s Cat)\n')

            with mock.patch('platform._UNIXCONFDIR', tempdir):
                with warnings.catch_warnings():
                    warnings.filterwarnings(
                        'ignore',
                        'dist\(\) and linux_distribution\(\) '
                        'functions are deprecated .*',
                        PendingDeprecationWarning,
                    )
                    distname, version, distid = platform.linux_distribution()

                self.assertEqual(distname, 'Fedora')
            self.assertEqual(version, '19')
            self.assertEqual(distid, 'Schr\xf6dinger\u2019s Cat') 
Example #14
Source File: tools.py    From Discord-SelfBot with MIT License 6 votes vote down vote up
def sysinfo(self, ctx):
        """Several interesting informations about your Host System."""
        process = psutil.Process(os.getpid())
        memory_usage = process.memory_full_info().uss / 1024**2
        avai = psutil.virtual_memory().total / 1024**2
        mepro = process.memory_percent()
        prosys = psutil.cpu_percent()
        sys = '%s %s' % (platform.linux_distribution(full_distribution_name=1)[0].title(), platform.linux_distribution(full_distribution_name=1)[1])
        embed = discord.Embed(title='\N{ELECTRIC LIGHT BULB} Host Info', colour=embedColor(self))
        embed.add_field(name='\N{CLOCK FACE THREE OCLOCK} UPTIME', value=getTimeDiff(datetime.datetime.fromtimestamp(int(process.create_time())), datetime.datetime.now()))
        embed.add_field(name='\N{DESKTOP COMPUTER} SYSTEM', value='{0}, {1}'.format(platform.system(), sys, platform.release()))
        embed.add_field(name='\N{FLOPPY DISK} MEMORY', value='{:.2f} MiB / {:.2f} MiB\nBot uses: {:.2f}%'.format(memory_usage, avai, mepro))
        embed.add_field(name='\N{DVD} CPU', value='{:.2f}%'.format(prosys))
        await edit(ctx, embed=embed, ttl=20)

    # Change Gamestatus - blank is no game 
Example #15
Source File: _global.py    From kiwix-build with GNU General Public License v3.0 6 votes vote down vote up
def backend():
    global _backend
    if _backend is not None:
        return _backend

    _platform = platform.system()
    if _platform == 'Windows':
        print('ERROR: kiwix-build is not intented to run on Windows platform.\n'
              'There is no backend for Windows, so we can\'t launch any commands.')
        sys.exit(0)
    if _platform == 'Linux':
        _platform, _, _ = platform.linux_distribution()
        _platform = _platform.lower()
        _backend = backends.Linux()

    return _backend 
Example #16
Source File: utils.py    From cloudify-manager with Apache License 2.0 6 votes vote down vote up
def plugin_installable_on_current_platform(plugin):
    dist, _, release = platform.linux_distribution(
        full_distribution_name=False)
    dist, release = dist.lower(), release.lower()

    # Mac OSX is a special case, in which plugin.distribution and
    # plugin.release will be None instead of ''
    if 'macosx' in plugin.supported_platform:
        dist = dist or None
        release = release or None

    return (plugin.supported_platform in ('any', 'manylinux1_x86_64') or all([
        plugin.supported_platform == wagon.get_platform(),
        plugin.distribution == dist,
        plugin.distribution_release == release
    ])) 
Example #17
Source File: distro_utils.py    From builds with GNU General Public License v3.0 6 votes vote down vote up
def detect_distribution():
    """
    Detect current system Linux distribution, including name, version,
    arch and endianness.
    """
    # TODO(maurosr): Replace platform module by some alternative like distro
    # (https://github.com/nir0s/distro) or maybe just implementing our own
    # solution => platform module is deprecated in python 3.5 and will be
    # removed in python 3.7
    distro, version, _ = platform.linux_distribution(full_distribution_name=0)
    architecture = platform.machine()

    # NOTE(maurosr): when it fails to detect the distro it defaults to the
    # distro and version arguments passsed as parameters - their default
    # values are empty strings.
    if not distro or not version or not architecture:
        raise exception.DistributionDetectionError
    return (distro, version, architecture) 
Example #18
Source File: services.py    From CTF_AWD_Platform with MIT License 6 votes vote down vote up
def get_platform():
    """
    Get the OS name, hostname and kernel
    """
    try:
        osname = " ".join(platform.linux_distribution())
        uname = platform.uname()

        if osname == '  ':
            osname = uname[0]

        data = {'osname': osname, 'hostname': uname[1], 'kernel': uname[2]}

    except Exception as err:
        data = str(err)

    return data 
Example #19
Source File: utils.py    From bash-lambda-layer with MIT License 6 votes vote down vote up
def validate_instance(params):
    if platform.system() == 'Linux':
        if 'Ubuntu' in platform.linux_distribution()[0]:
            params.system = Ubuntu(params)
        if 'Red Hat Enterprise Linux Server' in platform.linux_distribution()[0]:
            params.system = RHEL(params)
    elif platform.system() == 'Windows':
        params.system = Windows(params)
    if 'system' not in params:
        raise RuntimeError(
            System.UNSUPPORTED_SYSTEM_MSG
        )
    try:
        urlopen('http://169.254.169.254/latest/meta-data/', timeout=1)
        raise RuntimeError('Amazon EC2 instances are not supported.')
    except (URLError, timeout):
        pass 
Example #20
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def distribution_id():
            return platform.linux_distribution()[2] 
Example #21
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def distribution_version():
            return platform.linux_distribution()[1] 
Example #22
Source File: test_upgrades.py    From reconbf with Apache License 2.0 5 votes vote down vote up
def security_updates():
    try:
        distro, _version, version_name = platform.linux_distribution()
    except Exception:
        return TestResult(Result.SKIP, "Could not detect distribution")

    if distro in ('Ubuntu', 'Debian'):
        repos = _get_deb_repos()

        security_suite = version_name + '-security'
        found_security = False

        for repo in repos:
            if repo['type'] != 'deb':
                continue

            if distro == 'Ubuntu' and repo['suite'] == security_suite:
                found_security = True
                break
            if (distro == 'Debian' and 'http://security.debian.org' in
                    repo['uri']):
                found_security = True
                break

        if found_security:
            return TestResult(Result.PASS, "Security repo present")
        else:
            return TestResult(Result.FAIL,
                              "Upstream security repo not configured")

    else:
        return TestResult(Result.SKIP, "Unknown distribution") 
Example #23
Source File: __init__.py    From insights-core with Apache License 2.0 5 votes vote down vote up
def os_release(self):
        _, version, _ = linux_distribution()
        return findall("^[6-8]", version)[0] 
Example #24
Source File: wrap_apt.py    From squadron with MIT License 5 votes vote down vote up
def compatible():
    if(FAKE_RETURN):
        return False
    os = system()
    if os == 'Linux':
        dist = platform.linux_distribution()
        if(dist[0] == 'Debian' or dist[0] == 'Ubuntu'):
            return True
    return False 
Example #25
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def distribution_name():
            return platform.linux_distribution()[0] 
Example #26
Source File: test_upgrades.py    From reconbf with Apache License 2.0 5 votes vote down vote up
def reboot_required():
    try:
        distro, _version, _name = platform.linux_distribution()
    except Exception:
        return TestResult(Result.SKIP, "Could not detect distribution")

    if distro in ('Ubuntu', 'Debian'):
        if os.path.isfile('/var/run/reboot-required'):
            try:
                with open('/var/run/reboot-required.pkgs', 'r') as f:
                    packages = set(line.strip() for line in f.readlines())
            except Exception:
                packages = None

            if packages:
                packages = ', '.join(sorted(packages))
                msg = "Reboot is required to update: %s" % packages
            else:
                msg = "Reboot is required"
            return TestResult(Result.FAIL, msg)

        else:
            return TestResult(Result.PASS)

    else:
        return TestResult(Result.SKIP, "Unknown distribution") 
Example #27
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def distribution_version():
            return platform.linux_distribution()[1] 
Example #28
Source File: test_package_support.py    From reconbf with Apache License 2.0 5 votes vote down vote up
def test_supported_packages():
    try:
        distro, _version, _name = platform.linux_distribution()
    except Exception:
        return TestResult(Result.SKIP, "Could not detect distribution")

    if distro == 'Ubuntu':
        return _check_packages_ubuntu()
    else:
        return TestResult(Result.SKIP, "Unknown distribution") 
Example #29
Source File: crash_report.py    From openxenmanager with GNU General Public License v2.0 5 votes vote down vote up
def capture_exception(self, exception, value, tb):
        if not RAVEN_AVAILABLE:
            return
        report_errors = True
        if report_errors:
            if self._client is None:
                self._client = raven.Client(CrashReport.DSN,
                                            release=__version__)

            tags = {"os:name": platform.system(),
                    "os:release": platform.release(),
                    "python:version": "{}.{}.{}".format(sys.version_info[0],
                                                    sys.version_info[1],
                                                    sys.version_info[2]),
                    "python:bit": struct.calcsize("P") * 8,
                    "python:encoding": sys.getdefaultencoding(),
                    "python:frozen": "{}".format(hasattr(sys, "frozen"))}

            if sys.platform == 'win32':
                tags['os:win32'] = " ".join(platform.win32_ver())
            elif sys.platform == 'darwin':
                tags['os:mac'] = "{} {}".format(platform.mac_ver()[0], platform.mac_ver()[2])
            else:
                tags['os:linux'] = " ".join(platform.linux_distribution())

            self._client.tags_context(tags)
            try:
                report = self._client.captureException((exception, value, tb))
            except Exception as e:
                log.error("Can't send crash report to Sentry: {}".format(e))
                return
            log.info("Crash report sent with event ID: {}".format(
                self._client.get_ident(report))) 
Example #30
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def distribution_name():
            return platform.linux_distribution()[0]