如何在golang中找到sshd服务状态

i have the following code

package main

import (
    "os/exec"
    "fmt"
    "os"
)

func main() {
    cmd := exec.Command("systemctl", "check", "sshd")
    out, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Println("Cannot find process")
        os.Exit(1)
    }
    fmt.Printf("Status is: %s", string(out))
    fmt.Println("Starting Role")

If the service is down, program will exit, althrough i would like to get its status ( 'down' , 'inactive', etc)

If the service is up, program will not exit and will print ' active ' output

Any hints, please ?

You're exiting if exec.Command returns an error, but you're not checking the type of error returned. Per the docs:

If the command starts but does not complete successfully, the error is of type *ExitError. Other error types may be returned for other situations.

Rather than just exiting, you should check if the error corresponds to a non-zero exit code from systemctl or a problem running it. This can be done with the following:

func main() {
  cmd := exec.Command("systemctl", "check", "sshd")
  out, err := cmd.CombinedOutput()
  if err != nil {
    if exitErr, ok := err.(*exec.ExitError); ok {
      fmt.Printf("systemctl finished with non-zero: %v
", exitErr)
    } else {
      fmt.Printf("failed to run systemctl: %v", err)
      os.Exit(1)
    }
  }
  fmt.Printf("Status is: %s
", string(out))
}