distro.py 42 KB

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