Python distro.linux_distribution() Examples
The following are 24
code examples of distro.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
distro
, or try the search function
.
Example #1
Source File: utilities.py From alibuild with GNU General Public License v3.0 | 6 votes |
def detectArch(): try: with open("/etc/os-release") as osr: osReleaseLines = osr.readlines() hasOsRelease = True except (IOError,OSError): osReleaseLines = [] hasOsRelease = False try: import platform if platform.system() == "Darwin": return "osx_x86-64" except: pass try: import platform, distro platformTuple = distro.linux_distribution() platformSystem = platform.system() platformProcessor = platform.processor() if " " in platformProcessor: platformProcessor = platform.machine() return doDetectArch(hasOsRelease, osReleaseLines, platformTuple, platformSystem, platformProcessor) except: return doDetectArch(hasOsRelease, osReleaseLines, ["unknown", "", ""], "", "")
Example #2
Source File: utilities.py From colcon-bundle with Apache License 2.0 | 6 votes |
def get_ubuntu_distribution_version(): """ Discover and return Ubuntu distribution version. :return: the Ubuntu distribution version of the build server. example: xenial, bionic """ import distro distribution = distro.linux_distribution() if distribution[0] == 'Ubuntu' and distribution[1] == '16.04': return 'xenial' elif distribution[0] == 'Ubuntu' and distribution[1] == '18.04': return 'bionic' elif distribution[0] == 'Ubuntu' and distribution[1] == '20.04': return 'focal' else: raise ValueError('Unsupported distribution', distribution)
Example #3
Source File: telemetry.py From review with Mozilla Public License 2.0 | 6 votes |
def set_os(self): """Collect human readable information about the OS version. For Linux it is setting a distribution name and version. """ system, node, release, version, machine, processor = platform.uname() if system == "Linux": distribution_name, distribution_number, _ = distro.linux_distribution( full_distribution_name=False ) distribution_version = " ".join([distribution_name, distribution_number]) elif system == "Windows": _release, distribution_version, _csd, _ptype = platform.win32_ver() elif system == "Darwin": distribution_version, _versioninfo, _machine = platform.mac_ver() else: distribution_version = release self.metrics.mozphab.environment.distribution_version.set(distribution_version)
Example #4
Source File: utils.py From Mobile-Security-Framework-MobSF with GNU General Public License v3.0 | 6 votes |
def print_version(): """Print MobSF Version.""" logger.info(settings.BANNER) ver = settings.MOBSF_VER if platform.system() == 'Windows': logger.info('Mobile Security Framework %s', ver) print('REST API Key: ' + api_key()) else: logger.info('\033[1m\033[34mMobile Security Framework %s\033[0m', ver) print('REST API Key: ' + Color.BOLD + api_key() + Color.END) logger.info('OS: %s', platform.system()) logger.info('Platform: %s', platform.platform()) dist = distro.linux_distribution(full_distribution_name=False) if dist: logger.info('Dist: %s', ' '.join(dist)) find_java_binary() check_basic_env() thread = threading.Thread(target=check_update, name='check_update') thread.start()
Example #5
Source File: __init__.py From python-zulip-api with Apache License 2.0 | 6 votes |
def get_user_agent(self) -> str: vendor = '' vendor_version = '' try: vendor = platform.system() vendor_version = platform.release() except OSError: # If the calling process is handling SIGCHLD, platform.system() can # fail with an IOError. See http://bugs.python.org/issue9127 pass if vendor == "Linux": vendor, vendor_version, dummy = distro.linux_distribution() elif vendor == "Windows": vendor_version = platform.win32_ver()[1] elif vendor == "Darwin": vendor_version = platform.mac_ver()[0] return "{client_name} ({vendor}; {vendor_version})".format( client_name=self.client_name, vendor=vendor, vendor_version=vendor_version, )
Example #6
Source File: base.py From raw-packet with MIT License | 5 votes |
def get_platform(self) -> str: """ Get your platform :return: Platform string (example: 'Windows 10' or 'Darwin 19.0.0' or 'Linux Ubuntu 18.04') """ if self._current_platform is None: linux_dist = linux_distribution() try: assert linux_dist[0] != '' and linux_dist[1] != '' and linux_dist[0] != system() self._current_platform = str(system()) + ' ' + str(linux_dist[0]) + ' ' + str(linux_dist[1]) except AssertionError: self._current_platform = str(system()) + ' ' + str(release()) return self._current_platform
Example #7
Source File: gen_commands.py From tethys with BSD 2-Clause "Simplified" License | 5 votes |
def gen_asgi_service(args): nginx_user = '' nginx_conf_path = '/etc/nginx/nginx.conf' if os.path.exists(nginx_conf_path): with open(nginx_conf_path, 'r') as nginx_conf: for line in nginx_conf.readlines(): tokens = line.split() if len(tokens) > 0 and tokens[0] == 'user': nginx_user = tokens[1].strip(';') break conda_prefix = args.conda_prefix if args.conda_prefix else get_environment_value('CONDA_PREFIX') conda_home = Path(conda_prefix).parents[1] user_option_prefix = '' try: linux_distro = linux_distribution(full_distribution_name=0)[0] if linux_distro in ['redhat', 'centos']: user_option_prefix = 'http-' except Exception: pass context = { 'nginx_user': nginx_user, 'port': args.tethys_port, 'asgi_processes': args.asgi_processes, 'conda_prefix': conda_prefix, 'conda_home': conda_home, 'tethys_src': TETHYS_SRC, 'tethys_home': TETHYS_HOME, 'user_option_prefix': user_option_prefix } return context
Example #8
Source File: work_load.py From FACT_core with GNU General Public License v3.0 | 5 votes |
def _get_platform_information(): operating_system = ' '.join(distro.linux_distribution()[0:2]) python_version = '.'.join(str(x) for x in sys.version_info[0:3]) fact_version = __VERSION__ return { 'os': operating_system, 'python': python_version, 'fact_version': fact_version }
Example #9
Source File: cli.py From mindmeld with Apache License 2.0 | 5 votes |
def _find_duckling_os_executable(): """Returns the correct duckling path for this OS.""" os_platform_name = "-".join( distro.linux_distribution(full_distribution_name=False) ).lower() for os_key in path.DUCKLING_OS_MAPPINGS: if os_key in os_platform_name: return path.DUCKLING_OS_MAPPINGS[os_key]
Example #10
Source File: wagon.py From wagon with Apache License 2.0 | 5 votes |
def _assert_linux_distribution_exists(): if linux_distribution is None: raise WagonError( 'Could not determine platform information. To build or ' 'repair wagons on python 3.8+, install distro (eg. by ' 'installing wagon[dist].')
Example #11
Source File: wagon.py From wagon with Apache License 2.0 | 5 votes |
def _get_os_properties(): """Retrieve distribution properties. **Note that platform.linux_distribution and platform.dist are deprecated and will be removed in Python 3.7. By that time, distro will become mandatory. """ return linux_distribution(full_distribution_name=False)
Example #12
Source File: user_agent.py From yandex-checkout-sdk-python with MIT License | 5 votes |
def __define_linux_os(): dist = distro.linux_distribution(full_distribution_name=False) os = Version(dist[0], dist[1]) return os
Example #13
Source File: utilities.py From power-up with Apache License 2.0 | 5 votes |
def pxelinux_set_local_boot(dir_path=None): """Disable PXE install by setting boot device to 'local' Args: dir_path (str, optional): Path to pxelinux directory """ if dir_path is None: if 'rhel' in linux_distribution(full_distribution_name=False): dir_path = '/var/lib/tftpboot/pxelinux.cfg/' if 'ubuntu' in linux_distribution(full_distribution_name=False): dir_path = '/tftpboot/pxelinux.cfg/' replace_regex(os.path.join(dir_path, 'default'), r'^DEFAULT.*$', 'DEFAULT local')
Example #14
Source File: platform.py From vaapi-fits with BSD 3-Clause "New" or "Revised" License | 5 votes |
def info(): import platform try: from distro import linux_distribution as linux_dist except: try: from platform import dist as linux_dist except: linux_dist = lambda: "unknown" try: import cpuinfo cpu = cpuinfo.get_cpu_info()["brand"] except: cpu = "unknown" from .common import get_media plinfo = dict() infofile = os.path.abspath( os.path.join( os.path.dirname(__file__), "caps", str(get_media()._get_platform_name()), "info" ) ) if os.path.exists(infofile): with open(infofile, 'rb') as f: exec(f.read(), plinfo) return dict( node = str(platform.node()), kernel = str(platform.release()), dist = str(linux_dist()), cpu = cpu, driver = str(get_media()._get_driver_name()), platform = str(get_media()._get_platform_name()), **plinfo.get("info", dict()), )
Example #15
Source File: util.py From tabula-py with MIT License | 5 votes |
def environment_info(): """Show environment information for reporting. Returns: str: Detailed information like Python version, Java version, or OS environment, etc. """ import sys import distro from tabula import __version__ print( """Python version: {} Java version: {} tabula-py version: {} platform: {} uname: {} linux_distribution: {} mac_ver: {} """.format( sys.version, java_version().strip(), __version__, platform.platform(), str(platform.uname()), distro.linux_distribution(), platform.mac_ver(), ) )
Example #16
Source File: util.py From mock with GNU General Public License v2.0 | 5 votes |
def is_host_rh_family(): distro_name = distro.linux_distribution(full_distribution_name=False)[0] return distro_name in RHEL_CLONES + ['fedora']
Example #17
Source File: migration_tool.py From indy-node with Apache License 2.0 | 5 votes |
def _get_current_platform(): name = distro.linux_distribution()[0] if 'Ubuntu' in name or 'ubuntu' in name: return 'Ubuntu' raise Exception('Platform is not supported')
Example #18
Source File: test_overcloud_host_configure.py From kayobe with Apache License 2.0 | 5 votes |
def _is_dnf(): info = distro.linux_distribution() return info[0] == 'CentOS Linux' and info[1].startswith('8')
Example #19
Source File: utilities.py From power-up with Apache License 2.0 | 4 votes |
def pxelinux_set_default(server, kernel, initrd, kickstart=None, kopts=None, dir_path=None): """Create default pxelinux profile This function assumes that the server is hosting the kernel, initrd, and kickstart (if specified) over http. The default 'dir_path' requires root access. Args: server (str): IP or hostname of http server hosting files kernel (str): HTTP path to installer kernel initrd (str): HTTP path to installer initrd kickstart (str, optional): HTTP path to installer kickstart kopts (str, optional): Any additional kernel options dir_path (str, optional): Path to pxelinux directory """ if dir_path is None: if 'rhel' in linux_distribution(full_distribution_name=False): dir_path = '/var/lib/tftpboot/pxelinux.cfg/' if 'ubuntu' in linux_distribution(full_distribution_name=False): dir_path = '/tftpboot/pxelinux.cfg/' kopts_base = (f"ksdevice=bootif lang= kssendmac text") if kickstart is not None: if 'ubuntu' in kernel.lower(): ks_key = 'url' else: ks_key = 'ks' kopts_base += f" {ks_key}=http://{server}/{kickstart}" if kopts is not None: kopts = kopts_base + f" {kopts}" else: kopts = kopts_base default = os.path.join(dir_path, 'default') os.makedirs(dir_path, exist_ok=True) with open(default, 'w') as file_object: file_object.write(dedent(f"""\ DEFAULT {kernel.split('/')[1]} LABEL local MENU LABEL (local) MENU DEFAULT LOCALBOOT -1 LABEL {kernel.split('/')[1]} MENU LABEL PXE Install: {kernel.split('/')[1]} KERNEL http://{server}/{kernel} INITRD http://{server}/{initrd} IPAPPEND 2 APPEND {kopts} """))
Example #20
Source File: nginx_setup.py From power-up with Apache License 2.0 | 4 votes |
def nginx_setup(root_dir='/srv', repo_id='nginx'): """Install and setup nginx http server Args: root_dir (str): Path to root directory for requests repo_id (str): Name of nginx yum repository Returns: int: Return code from 'systemctl restart nginx.service' """ log = logger.getlogger() # Check if nginx installed. Install if necessary. cmd = 'nginx -v' try: resp, err, rc = sub_proc_exec(cmd) except OSError: if 'rhel' in linux_distribution(full_distribution_name=False): cmd = 'yum -y install nginx' resp, err, rc = sub_proc_exec(cmd) if rc != 0: setup_nginx_yum_repo(root_dir, repo_id) cmd = 'yum -y install nginx' resp, err, rc = sub_proc_exec(cmd) if rc != 0: log.error('Failed installing nginx') log.error(resp) sys.exit(1) elif 'ubuntu' in linux_distribution(full_distribution_name=False): for cmd in ['apt-get update', 'apt-get install -y nginx']: resp, err, rc = sub_proc_exec(cmd) if rc != 0: log.error(f"A problem occured while running '{cmd}'") log.error(f'Response: {resp}\nError: {err}\nRC: {rc}') cmd = 'systemctl enable nginx.service' resp, err, rc = sub_proc_exec(cmd) if rc != 0: log.error('Failed to enable nginx service') cmd = 'systemctl start nginx.service' resp, err, rc = sub_proc_exec(cmd) if rc != 0: log.error('Failed to start nginx service') if os.path.isfile('/etc/nginx/conf.d/default.conf'): try: os.rename('/etc/nginx/conf.d/default.conf', '/etc/nginx/conf.d/default.conf.bak') except OSError: log.warning('Failed renaming /etc/nginx/conf.d/default.conf') nginx_location = {'/': [f'root {root_dir}', 'autoindex on']} nginx_directives = {'listen': '80', 'server_name': 'powerup'} rc = nginx_modify_conf('/etc/nginx/conf.d/server1.conf', directives=nginx_directives, locations=nginx_location) return rc
Example #21
Source File: utilities.py From power-up with Apache License 2.0 | 4 votes |
def firewall_add_services(services): """Add services to be allowed in firewall rules Args: services (str or list): Service(s) to be permanently allowed Returns: int: Binary error code """ if type(services) is str: services = [services] fw_err = 0 if 'rhel' in linux_distribution(full_distribution_name=False): firewall_service = 'firewalld.service' firewall_enable_cmd = 'firewall-cmd --permanent --add-service=' firewall_reload_cmd = 'firewall-cmd --reload' elif 'ubuntu' in linux_distribution(full_distribution_name=False): firewall_service = 'ufw.service' firewall_enable_cmd = 'ufw allow ' firewall_reload_cmd = 'true' return 0 # TODO: Need to add firewall configuration for Ubuntu cmd = f'systemctl status {firewall_service}' resp, err, rc = sub_proc_exec(cmd) if 'Active: active (running)' in resp.splitlines()[2]: LOG.debug('Firewall is running') else: cmd = f'systemctl enable {firewall_service}' resp, err, rc = sub_proc_exec(cmd) if rc != 0: fw_err += 1 LOG.error('Failed to enable firewall service') cmd = f'systemctl start {firewall_service}' resp, err, rc = sub_proc_exec(cmd) if rc != 0: fw_err += 10 LOG.error('Failed to start firewall') for service in services: cmd = f'{firewall_enable_cmd}{service}' resp, err, rc = sub_proc_exec(cmd) if rc != 0: fw_err += 100 LOG.error(f'Failed to enable {service} service on firewall') resp, err, rc = sub_proc_exec(firewall_reload_cmd) if 'success' not in resp: fw_err += 1000 LOG.error('Error attempting to restart firewall') return fw_err
Example #22
Source File: gtk.py From system76-driver with GNU General Public License v2.0 | 4 votes |
def __init__(self, model, product, args): assert isinstance(model, str) assert product is None or isinstance(product, dict) assert isinstance(args.dry, bool) self.thread = None self.model = model self.product = product self.args = args self.builder = Gtk.Builder() self.builder.add_from_file(get_datafile('gtk3.glade')) self.window = self.builder.get_object('mainWindow') self.notify_icon = self.builder.get_object('notifyImage') self.notify_text = self.builder.get_object('notifyLabel') self.details = self.builder.get_object('detailsText') self.builder.get_object('sysModel').set_text(model) self.builder.get_object('ubuntuVersion').set_text( '{} {} ({})'.format(*distro.linux_distribution()) ) self.builder.get_object('driverVersion').set_text(__version__) self.builder.connect_signals({ 'onDeleteWindow': Gtk.main_quit, 'onCloseClicked': Gtk.main_quit, 'onInstallClicked': self.onInstallClicked, 'onRestoreClicked': self.onRestoreClicked, 'onCreateClicked': self.onCreateClicked, 'onAboutClicked': self.onAboutClicked, }) self.buttons = dict( (key, self.builder.get_object(key)) for key in ['driverInstall', 'driverRestore', 'driverCreate'] ) self.enabled = { 'driverInstall': False, 'driverRestore': False, 'driverCreate': False, } self.set_sensitive(False) if product: name = product['name'] else: name = _('Non System76 Product') self.set_notify('gtk-dialog-error', _('Not a System76 product, nothing to do!') ) self.builder.get_object('sysName').set_text(name)
Example #23
Source File: test_gtk.py From system76-driver with GNU General Public License v2.0 | 4 votes |
def test_init(self): args = DummyArgs('/home/oem', False) product = { 'name': 'Gazelle Professional', 'drivers': [], 'prefs': [], } ui = gtk.UI('gazp9', product, args) self.assertIsNone(ui.thread) self.assertEqual(ui.model, 'gazp9') self.assertIs(ui.product, product) self.assertIs(ui.args, args) self.assertIsInstance(ui.builder, Gtk.Builder) self.assertIsInstance(ui.window, Gtk.Window) self.assertEqual( ui.builder.get_object('sysName').get_text(), 'Gazelle Professional' ) self.assertEqual( ui.builder.get_object('sysModel').get_text(), 'gazp9' ) self.assertEqual( ui.builder.get_object('ubuntuVersion').get_text(), '{} {} ({})'.format(*distro.linux_distribution()) ) self.assertEqual( ui.builder.get_object('driverVersion').get_text(), system76driver.__version__ ) model = random_id() name = random_id() product = {'name': name} ui = gtk.UI(model, product, args) self.assertIsNone(ui.thread) self.assertEqual(ui.model, model) self.assertIs(ui.product, product) self.assertEqual(ui.product, {'name': name}) self.assertIs(ui.args, args) self.assertIsInstance(ui.builder, Gtk.Builder) self.assertIsInstance(ui.window, Gtk.Window) self.assertEqual(ui.builder.get_object('sysName').get_text(), name) self.assertEqual(ui.builder.get_object('sysModel').get_text(), model) self.assertEqual( ui.builder.get_object('ubuntuVersion').get_text(), '{} {} ({})'.format(*distro.linux_distribution()) ) self.assertEqual( ui.builder.get_object('driverVersion').get_text(), system76driver.__version__ )
Example #24
Source File: util.py From mock with GNU General Public License v2.0 | 4 votes |
def _prepare_nspawn_command(chrootPath, user, cmd, nspawn_args=None, env=None, cwd=None, interactive=False, shell=False): nspawn_argv = ['/usr/bin/systemd-nspawn', '-q', '-M', uuid.uuid4().hex, '-D', chrootPath] distro_label = distro.linux_distribution(full_distribution_name=False)[0] try: distro_version = float(distro.version() or 0) except ValueError: distro_version = 0 if distro_label not in RHEL_CLONES or distro_version >= 7.5: # EL < 7.5 does not support the nspawn -a option. See BZ 1417387 nspawn_argv += ['-a'] if user: # user can be either id or name nspawn_argv += ['-u', str(user)] if nspawn_args: nspawn_argv.extend(nspawn_args) if _check_nspawn_pipe_option(): if not interactive or not (sys.stdin.isatty() and sys.stdout.isatty()): nspawn_argv += ['--console=pipe'] if cwd: nspawn_argv.append('--chdir={0}'.format(cwd)) if env: for k, v in env.items(): nspawn_argv.append('--setenv={0}={1}'.format(k, v)) # The '/bin/sh -c' wrapper is explicitly requested (--shell). In this case # we shrink the list of arguments into one shell command, so the command is # completely shell-expanded. if shell and isinstance(cmd, list): cmd = ' '.join(cmd) # HACK! No matter if --shell/--chroot is used, we have documented that we # shell-expand the CMD if there are no ARGS. This is historical # requirement that other people probably depend on. if isinstance(cmd, str): cmd = ['/bin/sh', '-c', cmd] return nspawn_argv + cmd