Get Linux Distribution Name and Version with Python

Since Debian 10 Buster there is no minor version number in lsb_release output or /etc/os-release anymore. Bug has been filed, but apparently there is no will to get the full version number back.

The dist() and linux_distribution() functions in the platform module in Python have been deprecated in 3.5 and removed in 3.8.0:

$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.dist()
__main__:1: DeprecationWarning: dist() and linux_distribution() functions are deprecated in Python 3.5
('debian', '10.1', '')

Also, the distro package in PyPI didn’t provide the correct output as I tested it briefly.

Hence, here is my own for getting the inventory data correct with our Linux servers:

import csv


with open("/etc/os-release") as f:
    reader = csv.reader(f, delimiter="=")
    for row in reader:
        RELEASE_DATA[row[0]] = row[1]

if RELEASE_DATA["ID"] in ["debian", "raspbian"]:
    with open("/etc/debian_version") as f:
        DEBIAN_VERSION = f.readline().strip()
    major_version = DEBIAN_VERSION.split(".")[0]
    version_split = RELEASE_DATA["VERSION"].split(" ", maxsplit=1)
    if version_split[0] == major_version:
        # Just major version shown, replace it with the full version
        RELEASE_DATA["VERSION"] = " ".join([DEBIAN_VERSION] + version_split[1:])

print("{} {}".format(RELEASE_DATA["NAME"], RELEASE_DATA["VERSION"]))

Example outputs:

On Ubuntu 18.04.3:

$ lsb_release -ds
Ubuntu 18.04.3 LTS
$ python3
Ubuntu 18.04.3 LTS (Bionic Beaver)

On Debian 9.11 Stretch:

$ lsb_release -ds
Debian GNU/Linux 9.11 (stretch)
$ python3
Debian GNU/Linux 9.11 (stretch)

On Debian 10.1 Buster:

$ lsb_release -ds
Debian GNU/Linux 10 (buster)
$ python3
Debian GNU/Linux 10.1 (buster)

Feel free to comment below with other Linux distribution outputs.

Leave a Reply