Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在golang查找sshd服务状态_Go - Fatal编程技术网

如何在golang查找sshd服务状态

如何在golang查找sshd服务状态,go,Go,我有以下代码 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(

我有以下代码

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")
如果服务关闭,程序将退出,尽管我想获取其状态(“关闭”、“不活动”等)

如果服务启动,程序将不会退出,并将打印“活动”输出


有什么提示吗?

如果
exec.Command
返回错误,您将退出,但您没有检查返回的错误类型。 根据:

如果命令启动但未成功完成,则错误为 属于恐怖分子。对于其他错误类型,可能会返回其他错误类型 情况

您应该检查错误是否对应于来自
systemctl
的非零退出代码或运行该代码时出现的问题,而不仅仅是退出。这可以通过以下方式完成:

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\n", exitErr)
    } else {
      fmt.Printf("failed to run systemctl: %v", err)
      os.Exit(1)
    }
  }
  fmt.Printf("Status is: %s\n", string(out))
}