distro.py 48 KB

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