go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/id/hostname/hostname.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package hostname
     5  
     6  import (
     7  	"io"
     8  	"strings"
     9  
    10  	"github.com/rs/zerolog/log"
    11  	"github.com/spf13/afero"
    12  	"go.mondoo.com/cnquery/providers-sdk/v1/inventory"
    13  	"go.mondoo.com/cnquery/providers/os/connection/shared"
    14  )
    15  
    16  func Hostname(conn shared.Connection, pf *inventory.Platform) (string, bool) {
    17  	var hostname string
    18  
    19  	if !pf.IsFamily(inventory.FAMILY_UNIX) && !pf.IsFamily(inventory.FAMILY_WINDOWS) {
    20  		log.Warn().Msg("your platform is not supported for hostname detection")
    21  		return hostname, false
    22  	}
    23  
    24  	// linux:
    25  	// we prefer the hostname over /etc/hostname since systemd is not updating the value all the time
    26  	//
    27  	// windows:
    28  	// hostname command works more reliable than t.RunCommand("powershell -c \"$env:computername\"")
    29  	// since it will return a non-zero exit code.
    30  	cmd, err := conn.RunCommand("hostname")
    31  	if err == nil && cmd.ExitStatus == 0 {
    32  		data, err := io.ReadAll(cmd.Stdout)
    33  		if err == nil {
    34  			return strings.TrimSpace(string(data)), true
    35  		}
    36  	} else {
    37  		log.Debug().Err(err).Msg("could not run hostname command")
    38  	}
    39  
    40  	// try to use /etc/hostname since it's also working on static analysis
    41  	if pf.IsFamily(inventory.FAMILY_LINUX) {
    42  		afs := &afero.Afero{Fs: conn.FileSystem()}
    43  		ok, err := afs.Exists("/etc/hostname")
    44  		if err == nil && ok {
    45  			content, err := afs.ReadFile("/etc/hostname")
    46  			if err == nil {
    47  				return strings.TrimSpace(string(content)), true
    48  			}
    49  		} else {
    50  			log.Debug().Err(err).Msg("could not read /etc/hostname file")
    51  		}
    52  	}
    53  
    54  	return "", false
    55  }