How can I detect linux distribution within GOlang program?

5.7k Views Asked by At

I want to write linux distribution independant Golang code. I need detect which linux distribution and need to run distribution specific commands within program. Like dpkg in case of Ubuntu and rpm -q in case of RHEL.

4

There are 4 best solutions below

0
On

The package containing the executable lsb_release may or may not be installed on the system.

You could use the file /etc/os-release, which can be easily parsed with the library go-ini. See example:

import (
    "fmt"
    "github.com/go-ini/ini"
)

func ReadOSRelease(configfile string) map[string]string {
    cfg, err := ini.Load(configfile)
    if err != nil {
        log.Fatal("Fail to read file: ", err)
    }

    ConfigParams := make(map[string]string)
    ConfigParams["ID"] = cfg.Section("").Key("ID").String()

    return ConfigParams
}

OSInfo := ReadOSRelease("/etc/os-release")
OSRelease := OSInfo["ID"]

fmt.Print(OSRelease)
0
On

If you wanted to use a Go module, there's Sysinfo.

It collects all of the system info (without any dependencies) and gives you JSON which includes what you're looking for. Here's a snippet of that data:

"os": {
    "name": "CentOS Linux 7 (Core)",
    "vendor": "centos",
    "version": "7",
    "release": "7.2.1511",
    "architecture": "amd64"
  },
4
On

You can use exec.Cmd to run lsb_release -a or uname -a and parse the output to find out the distribution.

Reference

0
On

There's a convenient command line tool backed by a go library here: dekobon/distro-detect

Here's how the library is called in the main function of the command line

linux.FileSystemRoot = fsRoot
distro := linux.DiscoverDistro()

It parses both the os-release file and the lsb-release file declarations.