登录
首页 >  Golang >  Go问答

获取命令的标准输出的方法

来源:stackoverflow

时间:2024-03-21 16:48:33 434浏览 收藏

获取命令的标准输出的方法有多种。当使用 `Output` 函数时,它只返回标准输出。而 `CombinedOutput` 函数可以同时捕获标准输出和标准错误。如果需要继续使用 `Output` 函数,可以将错误转换为 `ExitError` 并同时检查 `ExitError.Stderr`。

问题内容

我有以下代码来检查与给定主机的 ssh 连接是否正常工作。

func IsSSHConnectionWorking(Host Host) bool {
    cmd :=
        fmt.Sprintf("ssh -o \"PasswordAuthentication no\" -i %s -p %s %s@%s", Host.IdentityFile, Host.Port, Host.User, Host.IP)

    fmt.Printf("Connecting to %s with %s", Host.IP, cmd)

    output, err := exec.Command("bash", "-c", cmd).Output()

    if err != nil {
        log.Println(err)
        log.Printf("Failed to connect to Host: %s\n Error: %s", Host.IP, output)
        return false
    }

    return true
}

我已经注意到,如果参数错误,则返回到程序的错误是 exit status 255 并且输出为空。

在 cli 本身上执行有问题的命令将返回 user@host: permission returned (publickey,password).

有办法捕捉到这个吗?


解决方案


请尝试改用 CombinedOutput,因为这将捕获 stdout 和 stderr。同时,Output仅返回stdout。

https://golang.org/pkg/os/exec/#Cmd.CombinedOutput

如果您想继续使用 Output,请将错误转换为 ExitError 并同时检查 ExitError.Stderr。

https://golang.org/pkg/os/exec/#Cmd.Output

好了,本文到此结束,带大家了解了《获取命令的标准输出的方法》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>