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

如何在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 ?

我有以下代码 p>

 包main 
 \  nimport(
“ os / exec” 
“ fmt” 
“ os” 
)
 
func main(){
 cmd:= exec.Command(“ systemctl”,“ check”,“ sshd”  )
输出,错误:= cmd.CombinedOutput()
,如果错误!= nil {
 fmt.Println(“无法找到进程”)
 os.Exit(1)
} 
 fmt.Printf(  “状态为:%s”,字符串(输出))
 fmt.Println(“起始角色”)
  code>  pre> 
 
 

如果服务关闭,程序将退出 ,直到我一直想获得其状态(“关闭”,“无效”等) p>

如果该服务已启动,程序将不会退出,并且会显示“有效”输出 p>

有任何提示吗? p> div>

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))
}