distro.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. #!/usr/bin/env python
  2. # Copyright 2015,2016,2017 Nir Cohen
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """
  16. The ``distro`` package (``distro`` stands for Linux Distribution) provides
  17. information about the Linux distribution it runs on, such as a reliable
  18. machine-readable distro ID, or version information.
  19. It is the recommended replacement for Python's original
  20. :py:func:`platform.linux_distribution` function, but it provides much more
  21. functionality. An alternative implementation became necessary because Python
  22. 3.5 deprecated this function, and Python 3.8 removed it altogether. Its
  23. predecessor function :py:func:`platform.dist` was already deprecated since
  24. Python 2.6 and removed in Python 3.8. Still, there are many cases in which
  25. access to OS distribution information is needed. See `Python issue 1322
  26. <https://bugs.python.org/issue1322>`_ for more information.
  27. """
  28. import argparse
  29. import json
  30. import logging
  31. import os
  32. import re
  33. import shlex
  34. import subprocess
  35. import sys
  36. import warnings
  37. from typing import (
  38. Any,
  39. Callable,
  40. Dict,
  41. Iterable,
  42. Optional,
  43. Sequence,
  44. TextIO,
  45. Tuple,
  46. Type,
  47. )
  48. try:
  49. from typing import TypedDict
  50. except ImportError:
  51. # Python 3.7
  52. TypedDict = dict
  53. __version__ = "1.8.0"
  54. class VersionDict(TypedDict):
  55. major: str
  56. minor: str
  57. build_number: str
  58. class InfoDict(TypedDict):
  59. id: str
  60. version: str
  61. version_parts: VersionDict
  62. like: str
  63. codename: str
  64. _UNIXCONFDIR = os.environ.get("UNIXCONFDIR", "/etc")
  65. _UNIXUSRLIBDIR = os.environ.get("UNIXUSRLIBDIR", "/usr/lib")
  66. _OS_RELEASE_BASENAME = "os-release"
  67. #: Translation table for normalizing the "ID" attribute defined in os-release
  68. #: files, for use by the :func:`distro.id` method.
  69. #:
  70. #: * Key: Value as defined in the os-release file, translated to lower case,
  71. #: with blanks translated to underscores.
  72. #:
  73. #: * Value: Normalized value.
  74. NORMALIZED_OS_ID = {
  75. "ol": "oracle", # Oracle Linux
  76. "opensuse-leap": "opensuse", # Newer versions of OpenSuSE report as opensuse-leap
  77. }
  78. #: Translation table for normalizing the "Distributor ID" attribute returned by
  79. #: the lsb_release command, for use by the :func:`distro.id` method.
  80. #:
  81. #: * Key: Value as returned by the lsb_release command, translated to lower
  82. #: case, with blanks translated to underscores.
  83. #:
  84. #: * Value: Normalized value.
  85. NORMALIZED_LSB_ID = {
  86. "enterpriseenterpriseas": "oracle", # Oracle Enterprise Linux 4
  87. "enterpriseenterpriseserver": "oracle", # Oracle Linux 5
  88. "redhatenterpriseworkstation": "rhel", # RHEL 6, 7 Workstation
  89. "redhatenterpriseserver": "rhel", # RHEL 6, 7 Server
  90. "redhatenterprisecomputenode": "rhel", # RHEL 6 ComputeNode
  91. }
  92. #: Translation table for normalizing the distro ID derived from the file name
  93. #: of distro release files, for use by the :func:`distro.id` method.
  94. #:
  95. #: * Key: Value as derived from the file name of a distro release file,
  96. #: translated to lower case, with blanks translated to underscores.
  97. #:
  98. #: * Value: Normalized value.
  99. NORMALIZED_DISTRO_ID = {
  100. "redhat": "rhel", # RHEL 6.x, 7.x
  101. }
  102. # Pattern for content of distro release file (reversed)
  103. _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(
  104. r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)"
  105. )
  106. # Pattern for base file name of distro release file
  107. _DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r"(\w+)[-_](release|version)$")
  108. # Base file names to be looked up for if _UNIXCONFDIR is not readable.
  109. _DISTRO_RELEASE_BASENAMES = [
  110. "SuSE-release",
  111. "arch-release",
  112. "base-release",
  113. "centos-release",
  114. "fedora-release",
  115. "gentoo-release",
  116. "mageia-release",
  117. "mandrake-release",
  118. "mandriva-release",
  119. "mandrivalinux-release",
  120. "manjaro-release",
  121. "oracle-release",
  122. "redhat-release",
  123. "rocky-release",
  124. "sl-release",
  125. "slackware-version",
  126. ]
  127. # Base file names to be ignored when searching for distro release file
  128. _DISTRO_RELEASE_IGNORE_BASENAMES = (
  129. "debian_version",
  130. "lsb-release",
  131. "oem-release",
  132. _OS_RELEASE_BASENAME,
  133. "system-release",
  134. "plesk-release",
  135. "iredmail-release",
  136. )
  137. def linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]:
  138. """
  139. .. deprecated:: 1.6.0
  140. :func:`distro.linux_distribution()` is deprecated. It should only be
  141. used as a compatibility shim with Python's
  142. :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`,
  143. :func:`distro.version` and :func:`distro.name` instead.
  144. Return information about the current OS distribution as a tuple
  145. ``(id_name, version, codename)`` with items as follows:
  146. * ``id_name``: If *full_distribution_name* is false, the result of
  147. :func:`distro.id`. Otherwise, the result of :func:`distro.name`.
  148. * ``version``: The result of :func:`distro.version`.
  149. * ``codename``: The extra item (usually in parentheses) after the
  150. os-release version number, or the result of :func:`distro.codename`.
  151. The interface of this function is compatible with the original
  152. :py:func:`platform.linux_distribution` function, supporting a subset of
  153. its parameters.
  154. The data it returns may not exactly be the same, because it uses more data
  155. sources than the original function, and that may lead to different data if
  156. the OS distribution is not consistent across multiple data sources it
  157. provides (there are indeed such distributions ...).
  158. Another reason for differences is the fact that the :func:`distro.id`
  159. method normalizes the distro ID string to a reliable machine-readable value
  160. for a number of popular OS distributions.
  161. """
  162. warnings.warn(
  163. "distro.linux_distribution() is deprecated. It should only be used as a "
  164. "compatibility shim with Python's platform.linux_distribution(). Please use "
  165. "distro.id(), distro.version() and distro.name() instead.",
  166. DeprecationWarning,
  167. stacklevel=2,
  168. )
  169. return _distro.linux_distribution(full_distribution_name)
  170. def id() -> str:
  171. """
  172. Return the distro ID of the current distribution, as a
  173. machine-readable string.
  174. For a number of OS distributions, the returned distro ID value is
  175. *reliable*, in the sense that it is documented and that it does not change
  176. across releases of the distribution.
  177. This package maintains the following reliable distro ID values:
  178. ============== =========================================
  179. Distro ID Distribution
  180. ============== =========================================
  181. "ubuntu" Ubuntu
  182. "debian" Debian
  183. "rhel" RedHat Enterprise Linux
  184. "centos" CentOS
  185. "fedora" Fedora
  186. "sles" SUSE Linux Enterprise Server
  187. "opensuse" openSUSE
  188. "amzn" Amazon Linux
  189. "arch" Arch Linux
  190. "buildroot" Buildroot
  191. "cloudlinux" CloudLinux OS
  192. "exherbo" Exherbo Linux
  193. "gentoo" GenToo Linux
  194. "ibm_powerkvm" IBM PowerKVM
  195. "kvmibm" KVM for IBM z Systems
  196. "linuxmint" Linux Mint
  197. "mageia" Mageia
  198. "mandriva" Mandriva Linux
  199. "parallels" Parallels
  200. "pidora" Pidora
  201. "raspbian" Raspbian
  202. "oracle" Oracle Linux (and Oracle Enterprise Linux)
  203. "scientific" Scientific Linux
  204. "slackware" Slackware
  205. "xenserver" XenServer
  206. "openbsd" OpenBSD
  207. "netbsd" NetBSD
  208. "freebsd" FreeBSD
  209. "midnightbsd" MidnightBSD
  210. "rocky" Rocky Linux
  211. "aix" AIX
  212. "guix" Guix System
  213. ============== =========================================
  214. If you have a need to get distros for reliable IDs added into this set,
  215. or if you find that the :func:`distro.id` function returns a different
  216. distro ID for one of the listed distros, please create an issue in the
  217. `distro issue tracker`_.
  218. **Lookup hierarchy and transformations:**
  219. First, the ID is obtained from the following sources, in the specified
  220. order. The first available and non-empty value is used:
  221. * the value of the "ID" attribute of the os-release file,
  222. * the value of the "Distributor ID" attribute returned by the lsb_release
  223. command,
  224. * the first part of the file name of the distro release file,
  225. The so determined ID value then passes the following transformations,
  226. before it is returned by this method:
  227. * it is translated to lower case,
  228. * blanks (which should not be there anyway) are translated to underscores,
  229. * a normalization of the ID is performed, based upon
  230. `normalization tables`_. The purpose of this normalization is to ensure
  231. that the ID is as reliable as possible, even across incompatible changes
  232. in the OS distributions. A common reason for an incompatible change is
  233. the addition of an os-release file, or the addition of the lsb_release
  234. command, with ID values that differ from what was previously determined
  235. from the distro release file name.
  236. """
  237. return _distro.id()
  238. def name(pretty: bool = False) -> str:
  239. """
  240. Return the name of the current OS distribution, as a human-readable
  241. string.
  242. If *pretty* is false, the name is returned without version or codename.
  243. (e.g. "CentOS Linux")
  244. If *pretty* is true, the version and codename are appended.
  245. (e.g. "CentOS Linux 7.1.1503 (Core)")
  246. **Lookup hierarchy:**
  247. The name is obtained from the following sources, in the specified order.
  248. The first available and non-empty value is used:
  249. * If *pretty* is false:
  250. - the value of the "NAME" attribute of the os-release file,
  251. - the value of the "Distributor ID" attribute returned by the lsb_release
  252. command,
  253. - the value of the "<name>" field of the distro release file.
  254. * If *pretty* is true:
  255. - the value of the "PRETTY_NAME" attribute of the os-release file,
  256. - the value of the "Description" attribute returned by the lsb_release
  257. command,
  258. - the value of the "<name>" field of the distro release file, appended
  259. with the value of the pretty version ("<version_id>" and "<codename>"
  260. fields) of the distro release file, if available.
  261. """
  262. return _distro.name(pretty)
  263. def version(pretty: bool = False, best: bool = False) -> str:
  264. """
  265. Return the version of the current OS distribution, as a human-readable
  266. string.
  267. If *pretty* is false, the version is returned without codename (e.g.
  268. "7.0").
  269. If *pretty* is true, the codename in parenthesis is appended, if the
  270. codename is non-empty (e.g. "7.0 (Maipo)").
  271. Some distributions provide version numbers with different precisions in
  272. the different sources of distribution information. Examining the different
  273. sources in a fixed priority order does not always yield the most precise
  274. version (e.g. for Debian 8.2, or CentOS 7.1).
  275. Some other distributions may not provide this kind of information. In these
  276. cases, an empty string would be returned. This behavior can be observed
  277. with rolling releases distributions (e.g. Arch Linux).
  278. The *best* parameter can be used to control the approach for the returned
  279. version:
  280. If *best* is false, the first non-empty version number in priority order of
  281. the examined sources is returned.
  282. If *best* is true, the most precise version number out of all examined
  283. sources is returned.
  284. **Lookup hierarchy:**
  285. In all cases, the version number is obtained from the following sources.
  286. If *best* is false, this order represents the priority order:
  287. * the value of the "VERSION_ID" attribute of the os-release file,
  288. * the value of the "Release" attribute returned by the lsb_release
  289. command,
  290. * the version number parsed from the "<version_id>" field of the first line
  291. of the distro release file,
  292. * the version number parsed from the "PRETTY_NAME" attribute of the
  293. os-release file, if it follows the format of the distro release files.
  294. * the version number parsed from the "Description" attribute returned by
  295. the lsb_release command, if it follows the format of the distro release
  296. files.
  297. """
  298. return _distro.version(pretty, best)
  299. def version_parts(best: bool = False) -> Tuple[str, str, str]:
  300. """
  301. Return the version of the current OS distribution as a tuple
  302. ``(major, minor, build_number)`` with items as follows:
  303. * ``major``: The result of :func:`distro.major_version`.
  304. * ``minor``: The result of :func:`distro.minor_version`.
  305. * ``build_number``: The result of :func:`distro.build_number`.
  306. For a description of the *best* parameter, see the :func:`distro.version`
  307. method.
  308. """
  309. return _distro.version_parts(best)
  310. def major_version(best: bool = False) -> str:
  311. """
  312. Return the major version of the current OS distribution, as a string,
  313. if provided.
  314. Otherwise, the empty string is returned. The major version is the first
  315. part of the dot-separated version string.
  316. For a description of the *best* parameter, see the :func:`distro.version`
  317. method.
  318. """
  319. return _distro.major_version(best)
  320. def minor_version(best: bool = False) -> str:
  321. """
  322. Return the minor version of the current OS distribution, as a string,
  323. if provided.
  324. Otherwise, the empty string is returned. The minor version is the second
  325. part of the dot-separated version string.
  326. For a description of the *best* parameter, see the :func:`distro.version`
  327. method.
  328. """
  329. return _distro.minor_version(best)
  330. def build_number(best: bool = False) -> str:
  331. """
  332. Return the build number of the current OS distribution, as a string,
  333. if provided.
  334. Otherwise, the empty string is returned. The build number is the third part
  335. of the dot-separated version string.
  336. For a description of the *best* parameter, see the :func:`distro.version`
  337. method.
  338. """
  339. return _distro.build_number(best)
  340. def like() -> str:
  341. """
  342. Return a space-separated list of distro IDs of distributions that are
  343. closely related to the current OS distribution in regards to packaging
  344. and programming interfaces, for example distributions the current
  345. distribution is a derivative from.
  346. **Lookup hierarchy:**
  347. This information item is only provided by the os-release file.
  348. For details, see the description of the "ID_LIKE" attribute in the
  349. `os-release man page
  350. <http://www.freedesktop.org/software/systemd/man/os-release.html>`_.
  351. """
  352. return _distro.like()
  353. def codename() -> str:
  354. """
  355. Return the codename for the release of the current OS distribution,
  356. as a string.
  357. If the distribution does not have a codename, an empty string is returned.
  358. Note that the returned codename is not always really a codename. For
  359. example, openSUSE returns "x86_64". This function does not handle such
  360. cases in any special way and just returns the string it finds, if any.
  361. **Lookup hierarchy:**
  362. * the codename within the "VERSION" attribute of the os-release file, if
  363. provided,
  364. * the value of the "Codename" attribute returned by the lsb_release
  365. command,
  366. * the value of the "<codename>" field of the distro release file.
  367. """
  368. return _distro.codename()
  369. def info(pretty: bool = False, best: bool = False) -> InfoDict:
  370. """
  371. Return certain machine-readable information items about the current OS
  372. distribution in a dictionary, as shown in the following example:
  373. .. sourcecode:: python
  374. {
  375. 'id': 'rhel',
  376. 'version': '7.0',
  377. 'version_parts': {
  378. 'major': '7',
  379. 'minor': '0',
  380. 'build_number': ''
  381. },
  382. 'like': 'fedora',
  383. 'codename': 'Maipo'
  384. }
  385. The dictionary structure and keys are always the same, regardless of which
  386. information items are available in the underlying data sources. The values
  387. for the various keys are as follows:
  388. * ``id``: The result of :func:`distro.id`.
  389. * ``version``: The result of :func:`distro.version`.
  390. * ``version_parts -> major``: The result of :func:`distro.major_version`.
  391. * ``version_parts -> minor``: The result of :func:`distro.minor_version`.
  392. * ``version_parts -> build_number``: The result of
  393. :func:`distro.build_number`.
  394. * ``like``: The result of :func:`distro.like`.
  395. * ``codename``: The result of :func:`distro.codename`.
  396. For a description of the *pretty* and *best* parameters, see the
  397. :func:`distro.version` method.
  398. """
  399. return _distro.info(pretty, best)
  400. def os_release_info() -> Dict[str, str]:
  401. """
  402. Return a dictionary containing key-value pairs for the information items
  403. from the os-release file data source of the current OS distribution.
  404. See `os-release file`_ for details about these information items.
  405. """
  406. return _distro.os_release_info()
  407. def lsb_release_info() -> Dict[str, str]:
  408. """
  409. Return a dictionary containing key-value pairs for the information items
  410. from the lsb_release command data source of the current OS distribution.
  411. See `lsb_release command output`_ for details about these information
  412. items.
  413. """
  414. return _distro.lsb_release_info()
  415. def distro_release_info() -> Dict[str, str]:
  416. """
  417. Return a dictionary containing key-value pairs for the information items
  418. from the distro release file data source of the current OS distribution.
  419. See `distro release file`_ for details about these information items.
  420. """
  421. return _distro.distro_release_info()
  422. def uname_info() -> Dict[str, str]:
  423. """
  424. Return a dictionary containing key-value pairs for the information items
  425. from the distro release file data source of the current OS distribution.
  426. """
  427. return _distro.uname_info()
  428. def os_release_attr(attribute: str) -> str:
  429. """
  430. Return a single named information item from the os-release file data source
  431. of the current OS distribution.
  432. Parameters:
  433. * ``attribute`` (string): Key of the information item.
  434. Returns:
  435. * (string): Value of the information item, if the item exists.
  436. The empty string, if the item does not exist.
  437. See `os-release file`_ for details about these information items.
  438. """
  439. return _distro.os_release_attr(attribute)
  440. def lsb_release_attr(attribute: str) -> str:
  441. """
  442. Return a single named information item from the lsb_release command output
  443. data source of the current OS distribution.
  444. Parameters:
  445. * ``attribute`` (string): Key of the information item.
  446. Returns:
  447. * (string): Value of the information item, if the item exists.
  448. The empty string, if the item does not exist.
  449. See `lsb_release command output`_ for details about these information
  450. items.
  451. """
  452. return _distro.lsb_release_attr(attribute)
  453. def distro_release_attr(attribute: str) -> str:
  454. """
  455. Return a single named information item from the distro release file
  456. data source of the current OS distribution.
  457. Parameters:
  458. * ``attribute`` (string): Key of the information item.
  459. Returns:
  460. * (string): Value of the information item, if the item exists.
  461. The empty string, if the item does not exist.
  462. See `distro release file`_ for details about these information items.
  463. """
  464. return _distro.distro_release_attr(attribute)
  465. def uname_attr(attribute: str) -> str:
  466. """
  467. Return a single named information item from the distro release file
  468. data source of the current OS distribution.
  469. Parameters:
  470. * ``attribute`` (string): Key of the information item.
  471. Returns:
  472. * (string): Value of the information item, if the item exists.
  473. The empty string, if the item does not exist.
  474. """
  475. return _distro.uname_attr(attribute)
  476. try:
  477. from functools import cached_property
  478. except ImportError:
  479. # Python < 3.8
  480. class cached_property: # type: ignore
  481. """A version of @property which caches the value. On access, it calls the
  482. underlying function and sets the value in `__dict__` so future accesses
  483. will not re-call the property.
  484. """
  485. def __init__(self, f: Callable[[Any], Any]) -> None:
  486. self._fname = f.__name__
  487. self._f = f
  488. def __get__(self, obj: Any, owner: Type[Any]) -> Any:
  489. assert obj is not None, f"call {self._fname} on an instance"
  490. ret = obj.__dict__[self._fname] = self._f(obj)
  491. return ret
  492. class LinuxDistribution:
  493. """
  494. Provides information about a OS distribution.
  495. This package creates a private module-global instance of this class with
  496. default initialization arguments, that is used by the
  497. `consolidated accessor functions`_ and `single source accessor functions`_.
  498. By using default initialization arguments, that module-global instance
  499. returns data about the current OS distribution (i.e. the distro this
  500. package runs on).
  501. Normally, it is not necessary to create additional instances of this class.
  502. However, in situations where control is needed over the exact data sources
  503. that are used, instances of this class can be created with a specific
  504. distro release file, or a specific os-release file, or without invoking the
  505. lsb_release command.
  506. """
  507. def __init__(
  508. self,
  509. include_lsb: Optional[bool] = None,
  510. os_release_file: str = "",
  511. distro_release_file: str = "",
  512. include_uname: Optional[bool] = None,
  513. root_dir: Optional[str] = None,
  514. include_oslevel: Optional[bool] = None,
  515. ) -> None:
  516. """
  517. The initialization method of this class gathers information from the
  518. available data sources, and stores that in private instance attributes.
  519. Subsequent access to the information items uses these private instance
  520. attributes, so that the data sources are read only once.
  521. Parameters:
  522. * ``include_lsb`` (bool): Controls whether the
  523. `lsb_release command output`_ is included as a data source.
  524. If the lsb_release command is not available in the program execution
  525. path, the data source for the lsb_release command will be empty.
  526. * ``os_release_file`` (string): The path name of the
  527. `os-release file`_ that is to be used as a data source.
  528. An empty string (the default) will cause the default path name to
  529. be used (see `os-release file`_ for details).
  530. If the specified or defaulted os-release file does not exist, the
  531. data source for the os-release file will be empty.
  532. * ``distro_release_file`` (string): The path name of the
  533. `distro release file`_ that is to be used as a data source.
  534. An empty string (the default) will cause a default search algorithm
  535. to be used (see `distro release file`_ for details).
  536. If the specified distro release file does not exist, or if no default
  537. distro release file can be found, the data source for the distro
  538. release file will be empty.
  539. * ``include_uname`` (bool): Controls whether uname command output is
  540. included as a data source. If the uname command is not available in
  541. the program execution path the data source for the uname command will
  542. be empty.
  543. * ``root_dir`` (string): The absolute path to the root directory to use
  544. to find distro-related information files. Note that ``include_*``
  545. parameters must not be enabled in combination with ``root_dir``.
  546. * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command
  547. output is included as a data source. If the oslevel command is not
  548. available in the program execution path the data source will be
  549. empty.
  550. Public instance attributes:
  551. * ``os_release_file`` (string): The path name of the
  552. `os-release file`_ that is actually used as a data source. The
  553. empty string if no distro release file is used as a data source.
  554. * ``distro_release_file`` (string): The path name of the
  555. `distro release file`_ that is actually used as a data source. The
  556. empty string if no distro release file is used as a data source.
  557. * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter.
  558. This controls whether the lsb information will be loaded.
  559. * ``include_uname`` (bool): The result of the ``include_uname``
  560. parameter. This controls whether the uname information will
  561. be loaded.
  562. * ``include_oslevel`` (bool): The result of the ``include_oslevel``
  563. parameter. This controls whether (AIX) oslevel information will be
  564. loaded.
  565. * ``root_dir`` (string): The result of the ``root_dir`` parameter.
  566. The absolute path to the root directory to use to find distro-related
  567. information files.
  568. Raises:
  569. * :py:exc:`ValueError`: Initialization parameters combination is not
  570. supported.
  571. * :py:exc:`OSError`: Some I/O issue with an os-release file or distro
  572. release file.
  573. * :py:exc:`UnicodeError`: A data source has unexpected characters or
  574. uses an unexpected encoding.
  575. """
  576. self.root_dir = root_dir
  577. self.etc_dir = os.path.join(root_dir, "etc") if root_dir else _UNIXCONFDIR
  578. self.usr_lib_dir = (
  579. os.path.join(root_dir, "usr/lib") if root_dir else _UNIXUSRLIBDIR
  580. )
  581. if os_release_file:
  582. self.os_release_file = os_release_file
  583. else:
  584. etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME)
  585. usr_lib_os_release_file = os.path.join(
  586. self.usr_lib_dir, _OS_RELEASE_BASENAME
  587. )
  588. # NOTE: The idea is to respect order **and** have it set
  589. # at all times for API backwards compatibility.
  590. if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile(
  591. usr_lib_os_release_file
  592. ):
  593. self.os_release_file = etc_dir_os_release_file
  594. else:
  595. self.os_release_file = usr_lib_os_release_file
  596. self.distro_release_file = distro_release_file or "" # updated later
  597. is_root_dir_defined = root_dir is not None
  598. if is_root_dir_defined and (include_lsb or include_uname or include_oslevel):
  599. raise ValueError(
  600. "Including subprocess data sources from specific root_dir is disallowed"
  601. " to prevent false information"
  602. )
  603. self.include_lsb = (
  604. include_lsb if include_lsb is not None else not is_root_dir_defined
  605. )
  606. self.include_uname = (
  607. include_uname if include_uname is not None else not is_root_dir_defined
  608. )
  609. self.include_oslevel = (
  610. include_oslevel if include_oslevel is not None else not is_root_dir_defined
  611. )
  612. def __repr__(self) -> str:
  613. """Return repr of all info"""
  614. return (
  615. "LinuxDistribution("
  616. "os_release_file={self.os_release_file!r}, "
  617. "distro_release_file={self.distro_release_file!r}, "
  618. "include_lsb={self.include_lsb!r}, "
  619. "include_uname={self.include_uname!r}, "
  620. "include_oslevel={self.include_oslevel!r}, "
  621. "root_dir={self.root_dir!r}, "
  622. "_os_release_info={self._os_release_info!r}, "
  623. "_lsb_release_info={self._lsb_release_info!r}, "
  624. "_distro_release_info={self._distro_release_info!r}, "
  625. "_uname_info={self._uname_info!r}, "
  626. "_oslevel_info={self._oslevel_info!r})".format(self=self)
  627. )
  628. def linux_distribution(
  629. self, full_distribution_name: bool = True
  630. ) -> Tuple[str, str, str]:
  631. """
  632. Return information about the OS distribution that is compatible
  633. with Python's :func:`platform.linux_distribution`, supporting a subset
  634. of its parameters.
  635. For details, see :func:`distro.linux_distribution`.
  636. """
  637. return (
  638. self.name() if full_distribution_name else self.id(),
  639. self.version(),
  640. self._os_release_info.get("release_codename") or self.codename(),
  641. )
  642. def id(self) -> str:
  643. """Return the distro ID of the OS distribution, as a string.
  644. For details, see :func:`distro.id`.
  645. """
  646. def normalize(distro_id: str, table: Dict[str, str]) -> str:
  647. distro_id = distro_id.lower().replace(" ", "_")
  648. return table.get(distro_id, distro_id)
  649. distro_id = self.os_release_attr("id")
  650. if distro_id:
  651. return normalize(distro_id, NORMALIZED_OS_ID)
  652. distro_id = self.lsb_release_attr("distributor_id")
  653. if distro_id:
  654. return normalize(distro_id, NORMALIZED_LSB_ID)
  655. distro_id = self.distro_release_attr("id")
  656. if distro_id:
  657. return normalize(distro_id, NORMALIZED_DISTRO_ID)
  658. distro_id = self.uname_attr("id")
  659. if distro_id:
  660. return normalize(distro_id, NORMALIZED_DISTRO_ID)
  661. return ""
  662. def name(self, pretty: bool = False) -> str:
  663. """
  664. Return the name of the OS distribution, as a string.
  665. For details, see :func:`distro.name`.
  666. """
  667. name = (
  668. self.os_release_attr("name")
  669. or self.lsb_release_attr("distributor_id")
  670. or self.distro_release_attr("name")
  671. or self.uname_attr("name")
  672. )
  673. if pretty:
  674. name = self.os_release_attr("pretty_name") or self.lsb_release_attr(
  675. "description"
  676. )
  677. if not name:
  678. name = self.distro_release_attr("name") or self.uname_attr("name")
  679. version = self.version(pretty=True)
  680. if version:
  681. name = f"{name} {version}"
  682. return name or ""
  683. def version(self, pretty: bool = False, best: bool = False) -> str:
  684. """
  685. Return the version of the OS distribution, as a string.
  686. For details, see :func:`distro.version`.
  687. """
  688. versions = [
  689. self.os_release_attr("version_id"),
  690. self.lsb_release_attr("release"),
  691. self.distro_release_attr("version_id"),
  692. self._parse_distro_release_content(self.os_release_attr("pretty_name")).get(
  693. "version_id", ""
  694. ),
  695. self._parse_distro_release_content(
  696. self.lsb_release_attr("description")
  697. ).get("version_id", ""),
  698. self.uname_attr("release"),
  699. ]
  700. if self.uname_attr("id").startswith("aix"):
  701. # On AIX platforms, prefer oslevel command output.
  702. versions.insert(0, self.oslevel_info())
  703. elif self.id() == "debian" or "debian" in self.like().split():
  704. # On Debian-like, add debian_version file content to candidates list.
  705. versions.append(self._debian_version)
  706. version = ""
  707. if best:
  708. # This algorithm uses the last version in priority order that has
  709. # the best precision. If the versions are not in conflict, that
  710. # does not matter; otherwise, using the last one instead of the
  711. # first one might be considered a surprise.
  712. for v in versions:
  713. if v.count(".") > version.count(".") or version == "":
  714. version = v
  715. else:
  716. for v in versions:
  717. if v != "":
  718. version = v
  719. break
  720. if pretty and version and self.codename():
  721. version = f"{version} ({self.codename()})"
  722. return version
  723. def version_parts(self, best: bool = False) -> Tuple[str, str, str]:
  724. """
  725. Return the version of the OS distribution, as a tuple of version
  726. numbers.
  727. For details, see :func:`distro.version_parts`.
  728. """
  729. version_str = self.version(best=best)
  730. if version_str:
  731. version_regex = re.compile(r"(\d+)\.?(\d+)?\.?(\d+)?")
  732. matches = version_regex.match(version_str)
  733. if matches:
  734. major, minor, build_number = matches.groups()
  735. return major, minor or "", build_number or ""
  736. return "", "", ""
  737. def major_version(self, best: bool = False) -> str:
  738. """
  739. Return the major version number of the current distribution.
  740. For details, see :func:`distro.major_version`.
  741. """
  742. return self.version_parts(best)[0]
  743. def minor_version(self, best: bool = False) -> str:
  744. """
  745. Return the minor version number of the current distribution.
  746. For details, see :func:`distro.minor_version`.
  747. """
  748. return self.version_parts(best)[1]
  749. def build_number(self, best: bool = False) -> str:
  750. """
  751. Return the build number of the current distribution.
  752. For details, see :func:`distro.build_number`.
  753. """
  754. return self.version_parts(best)[2]
  755. def like(self) -> str:
  756. """
  757. Return the IDs of distributions that are like the OS distribution.
  758. For details, see :func:`distro.like`.
  759. """
  760. return self.os_release_attr("id_like") or ""
  761. def codename(self) -> str:
  762. """
  763. Return the codename of the OS distribution.
  764. For details, see :func:`distro.codename`.
  765. """
  766. try:
  767. # Handle os_release specially since distros might purposefully set
  768. # this to empty string to have no codename
  769. return self._os_release_info["codename"]
  770. except KeyError:
  771. return (
  772. self.lsb_release_attr("codename")
  773. or self.distro_release_attr("codename")
  774. or ""
  775. )
  776. def info(self, pretty: bool = False, best: bool = False) -> InfoDict:
  777. """
  778. Return certain machine-readable information about the OS
  779. distribution.
  780. For details, see :func:`distro.info`.
  781. """
  782. return dict(
  783. id=self.id(),
  784. version=self.version(pretty, best),
  785. version_parts=dict(
  786. major=self.major_version(best),
  787. minor=self.minor_version(best),
  788. build_number=self.build_number(best),
  789. ),
  790. like=self.like(),
  791. codename=self.codename(),
  792. )
  793. def os_release_info(self) -> Dict[str, str]:
  794. """
  795. Return a dictionary containing key-value pairs for the information
  796. items from the os-release file data source of the OS distribution.
  797. For details, see :func:`distro.os_release_info`.
  798. """
  799. return self._os_release_info
  800. def lsb_release_info(self) -> Dict[str, str]:
  801. """
  802. Return a dictionary containing key-value pairs for the information
  803. items from the lsb_release command data source of the OS
  804. distribution.
  805. For details, see :func:`distro.lsb_release_info`.
  806. """
  807. return self._lsb_release_info
  808. def distro_release_info(self) -> Dict[str, str]:
  809. """
  810. Return a dictionary containing key-value pairs for the information
  811. items from the distro release file data source of the OS
  812. distribution.
  813. For details, see :func:`distro.distro_release_info`.
  814. """
  815. return self._distro_release_info
  816. def uname_info(self) -> Dict[str, str]:
  817. """
  818. Return a dictionary containing key-value pairs for the information
  819. items from the uname command data source of the OS distribution.
  820. For details, see :func:`distro.uname_info`.
  821. """
  822. return self._uname_info
  823. def oslevel_info(self) -> str:
  824. """
  825. Return AIX' oslevel command output.
  826. """
  827. return self._oslevel_info
  828. def os_release_attr(self, attribute: str) -> str:
  829. """
  830. Return a single named information item from the os-release file data
  831. source of the OS distribution.
  832. For details, see :func:`distro.os_release_attr`.
  833. """
  834. return self._os_release_info.get(attribute, "")
  835. def lsb_release_attr(self, attribute: str) -> str:
  836. """
  837. Return a single named information item from the lsb_release command
  838. output data source of the OS distribution.
  839. For details, see :func:`distro.lsb_release_attr`.
  840. """
  841. return self._lsb_release_info.get(attribute, "")
  842. def distro_release_attr(self, attribute: str) -> str:
  843. """
  844. Return a single named information item from the distro release file
  845. data source of the OS distribution.
  846. For details, see :func:`distro.distro_release_attr`.
  847. """
  848. return self._distro_release_info.get(attribute, "")
  849. def uname_attr(self, attribute: str) -> str:
  850. """
  851. Return a single named information item from the uname command
  852. output data source of the OS distribution.
  853. For details, see :func:`distro.uname_attr`.
  854. """
  855. return self._uname_info.get(attribute, "")
  856. @cached_property
  857. def _os_release_info(self) -> Dict[str, str]:
  858. """
  859. Get the information items from the specified os-release file.
  860. Returns:
  861. A dictionary containing all information items.
  862. """
  863. if os.path.isfile(self.os_release_file):
  864. with open(self.os_release_file, encoding="utf-8") as release_file:
  865. return self._parse_os_release_content(release_file)
  866. return {}
  867. @staticmethod
  868. def _parse_os_release_content(lines: TextIO) -> Dict[str, str]:
  869. """
  870. Parse the lines of an os-release file.
  871. Parameters:
  872. * lines: Iterable through the lines in the os-release file.
  873. Each line must be a unicode string or a UTF-8 encoded byte
  874. string.
  875. Returns:
  876. A dictionary containing all information items.
  877. """
  878. props = {}
  879. lexer = shlex.shlex(lines, posix=True)
  880. lexer.whitespace_split = True
  881. tokens = list(lexer)
  882. for token in tokens:
  883. # At this point, all shell-like parsing has been done (i.e.
  884. # comments processed, quotes and backslash escape sequences
  885. # processed, multi-line values assembled, trailing newlines
  886. # stripped, etc.), so the tokens are now either:
  887. # * variable assignments: var=value
  888. # * commands or their arguments (not allowed in os-release)
  889. # Ignore any tokens that are not variable assignments
  890. if "=" in token:
  891. k, v = token.split("=", 1)
  892. props[k.lower()] = v
  893. if "version" in props:
  894. # extract release codename (if any) from version attribute
  895. match = re.search(r"\((\D+)\)|,\s*(\D+)", props["version"])
  896. if match:
  897. release_codename = match.group(1) or match.group(2)
  898. props["codename"] = props["release_codename"] = release_codename
  899. if "version_codename" in props:
  900. # os-release added a version_codename field. Use that in
  901. # preference to anything else Note that some distros purposefully
  902. # do not have code names. They should be setting
  903. # version_codename=""
  904. props["codename"] = props["version_codename"]
  905. elif "ubuntu_codename" in props:
  906. # Same as above but a non-standard field name used on older Ubuntus
  907. props["codename"] = props["ubuntu_codename"]
  908. return props
  909. @cached_property
  910. def _lsb_release_info(self) -> Dict[str, str]:
  911. """
  912. Get the information items from the lsb_release command output.
  913. Returns:
  914. A dictionary containing all information items.
  915. """
  916. if not self.include_lsb:
  917. return {}
  918. try:
  919. cmd = ("lsb_release", "-a")
  920. stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
  921. # Command not found or lsb_release returned error
  922. except (OSError, subprocess.CalledProcessError):
  923. return {}
  924. content = self._to_str(stdout).splitlines()
  925. return self._parse_lsb_release_content(content)
  926. @staticmethod
  927. def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]:
  928. """
  929. Parse the output of the lsb_release command.
  930. Parameters:
  931. * lines: Iterable through the lines of the lsb_release output.
  932. Each line must be a unicode string or a UTF-8 encoded byte
  933. string.
  934. Returns:
  935. A dictionary containing all information items.
  936. """
  937. props = {}
  938. for line in lines:
  939. kv = line.strip("\n").split(":", 1)
  940. if len(kv) != 2:
  941. # Ignore lines without colon.
  942. continue
  943. k, v = kv
  944. props.update({k.replace(" ", "_").lower(): v.strip()})
  945. return props
  946. @cached_property
  947. def _uname_info(self) -> Dict[str, str]:
  948. if not self.include_uname:
  949. return {}
  950. try:
  951. cmd = ("uname", "-rs")
  952. stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
  953. except OSError:
  954. return {}
  955. content = self._to_str(stdout).splitlines()
  956. return self._parse_uname_content(content)
  957. @cached_property
  958. def _oslevel_info(self) -> str:
  959. if not self.include_oslevel:
  960. return ""
  961. try:
  962. stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL)
  963. except (OSError, subprocess.CalledProcessError):
  964. return ""
  965. return self._to_str(stdout).strip()
  966. @cached_property
  967. def _debian_version(self) -> str:
  968. try:
  969. with open(
  970. os.path.join(self.etc_dir, "debian_version"), encoding="ascii"
  971. ) as fp:
  972. return fp.readline().rstrip()
  973. except FileNotFoundError:
  974. return ""
  975. @staticmethod
  976. def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]:
  977. if not lines:
  978. return {}
  979. props = {}
  980. match = re.search(r"^([^\s]+)\s+([\d\.]+)", lines[0].strip())
  981. if match:
  982. name, version = match.groups()
  983. # This is to prevent the Linux kernel version from
  984. # appearing as the 'best' version on otherwise
  985. # identifiable distributions.
  986. if name == "Linux":
  987. return {}
  988. props["id"] = name.lower()
  989. props["name"] = name
  990. props["release"] = version
  991. return props
  992. @staticmethod
  993. def _to_str(bytestring: bytes) -> str:
  994. encoding = sys.getfilesystemencoding()
  995. return bytestring.decode(encoding)
  996. @cached_property
  997. def _distro_release_info(self) -> Dict[str, str]:
  998. """
  999. Get the information items from the specified distro release file.
  1000. Returns:
  1001. A dictionary containing all information items.
  1002. """
  1003. if self.distro_release_file:
  1004. # If it was specified, we use it and parse what we can, even if
  1005. # its file name or content does not match the expected pattern.
  1006. distro_info = self._parse_distro_release_file(self.distro_release_file)
  1007. basename = os.path.basename(self.distro_release_file)
  1008. # The file name pattern for user-specified distro release files
  1009. # is somewhat more tolerant (compared to when searching for the
  1010. # file), because we want to use what was specified as best as
  1011. # possible.
  1012. match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
  1013. else:
  1014. try:
  1015. basenames = [
  1016. basename
  1017. for basename in os.listdir(self.etc_dir)
  1018. if basename not in _DISTRO_RELEASE_IGNORE_BASENAMES
  1019. and os.path.isfile(os.path.join(self.etc_dir, basename))
  1020. ]
  1021. # We sort for repeatability in cases where there are multiple
  1022. # distro specific files; e.g. CentOS, Oracle, Enterprise all
  1023. # containing `redhat-release` on top of their own.
  1024. basenames.sort()
  1025. except OSError:
  1026. # This may occur when /etc is not readable but we can't be
  1027. # sure about the *-release files. Check common entries of
  1028. # /etc for information. If they turn out to not be there the
  1029. # error is handled in `_parse_distro_release_file()`.
  1030. basenames = _DISTRO_RELEASE_BASENAMES
  1031. for basename in basenames:
  1032. match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
  1033. if match is None:
  1034. continue
  1035. filepath = os.path.join(self.etc_dir, basename)
  1036. distro_info = self._parse_distro_release_file(filepath)
  1037. # The name is always present if the pattern matches.
  1038. if "name" not in distro_info:
  1039. continue
  1040. self.distro_release_file = filepath
  1041. break
  1042. else: # the loop didn't "break": no candidate.
  1043. return {}
  1044. if match is not None:
  1045. distro_info["id"] = match.group(1)
  1046. # CloudLinux < 7: manually enrich info with proper id.
  1047. if "cloudlinux" in distro_info.get("name", "").lower():
  1048. distro_info["id"] = "cloudlinux"
  1049. return distro_info
  1050. def _parse_distro_release_file(self, filepath: str) -> Dict[str, str]:
  1051. """
  1052. Parse a distro release file.
  1053. Parameters:
  1054. * filepath: Path name of the distro release file.
  1055. Returns:
  1056. A dictionary containing all information items.
  1057. """
  1058. try:
  1059. with open(filepath, encoding="utf-8") as fp:
  1060. # Only parse the first line. For instance, on SLES there
  1061. # are multiple lines. We don't want them...
  1062. return self._parse_distro_release_content(fp.readline())
  1063. except OSError:
  1064. # Ignore not being able to read a specific, seemingly version
  1065. # related file.
  1066. # See https://github.com/python-distro/distro/issues/162
  1067. return {}
  1068. @staticmethod
  1069. def _parse_distro_release_content(line: str) -> Dict[str, str]:
  1070. """
  1071. Parse a line from a distro release file.
  1072. Parameters:
  1073. * line: Line from the distro release file. Must be a unicode string
  1074. or a UTF-8 encoded byte string.
  1075. Returns:
  1076. A dictionary containing all information items.
  1077. """
  1078. matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1])
  1079. distro_info = {}
  1080. if matches:
  1081. # regexp ensures non-None
  1082. distro_info["name"] = matches.group(3)[::-1]
  1083. if matches.group(2):
  1084. distro_info["version_id"] = matches.group(2)[::-1]
  1085. if matches.group(1):
  1086. distro_info["codename"] = matches.group(1)[::-1]
  1087. elif line:
  1088. distro_info["name"] = line.strip()
  1089. return distro_info
  1090. _distro = LinuxDistribution()
  1091. def main() -> None:
  1092. logger = logging.getLogger(__name__)
  1093. logger.setLevel(logging.DEBUG)
  1094. logger.addHandler(logging.StreamHandler(sys.stdout))
  1095. parser = argparse.ArgumentParser(description="OS distro info tool")
  1096. parser.add_argument(
  1097. "--json", "-j", help="Output in machine readable format", action="store_true"
  1098. )
  1099. parser.add_argument(
  1100. "--root-dir",
  1101. "-r",
  1102. type=str,
  1103. dest="root_dir",
  1104. help="Path to the root filesystem directory (defaults to /)",
  1105. )
  1106. args = parser.parse_args()
  1107. if args.root_dir:
  1108. dist = LinuxDistribution(
  1109. include_lsb=False,
  1110. include_uname=False,
  1111. include_oslevel=False,
  1112. root_dir=args.root_dir,
  1113. )
  1114. else:
  1115. dist = _distro
  1116. if args.json:
  1117. logger.info(json.dumps(dist.info(), indent=4, sort_keys=True))
  1118. else:
  1119. logger.info("Name: %s", dist.name(pretty=True))
  1120. distribution_version = dist.version(pretty=True)
  1121. logger.info("Version: %s", distribution_version)
  1122. distribution_codename = dist.codename()
  1123. logger.info("Codename: %s", distribution_codename)
  1124. if __name__ == "__main__":
  1125. main()