distro.py 47 KB

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