GoLang ssh:尽管将其设置为nil,仍然"必须指定HosKeyCallback"错误

use*_*006 5 ssh go

我正在尝试使用GoLang连接到远程服务器.在客户端配置中,除了用户和密码之外,我将HostKeyCallback设置为nil,以便它接受每个主机

config := &ssh.ClientConfig{

        User: user,

        HostKeyCallback: nil,

        Auth: []ssh.AuthMethod{

        publicKey,
    },
}
Run Code Online (Sandbox Code Playgroud)

但我一直收到这个错误.

Failed to dial: ssh: must specify HostKeyCallback
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

ctc*_*rry 13

HostKeyCallback的nil行为已更改:https://github.com/golang/go/issues/19767

如果您想允许任何主持人:

HostKeyCallback: ssh.InsecureIgnoreHostKey()
Run Code Online (Sandbox Code Playgroud)


col*_*tor 9

请注意ssh.InsecureIgnoreHostKey附带的警告:

...它不应该用于生产代码。

因此,请考虑强制执行 SSH 密钥验证。其实实现起来并不难:

// create human-readable SSH-key strings
func keyString(k ssh.PublicKey) string {
    return k.Type() + " " + base64.StdEncoding.EncodeToString(k.Marshal()) // e.g. "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTY...."
}


func trustedHostKeyCallback(trustedKey string) ssh.HostKeyCallback {

    if trustedKey == "" {
        return func(_ string, _ net.Addr, k ssh.PublicKey) error {
            log.Printf("WARNING: SSH-key verification is *NOT* in effect: to fix, add this trustedKey: %q", keyString(k))
            return nil
        }
    }

    return func(_ string, _ net.Addr, k ssh.PublicKey) error {
        ks := keyString(k)
        if trustedKey != ks {
            return fmt.Errorf("SSH-key verification: expected %q but got %q", trustedKey, ks)
        }

        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用:

// where `conf` is the main app config
sc := &ssh.ClientConfig{
    User:            conf.Username,
    Auth:            []ssh.AuthMethod{ssh.Password(conf.Password)},
    HostKeyCallback: trustedHostKeyCallback(conf.HostKey), // <- server-key goes here
    Timeout:         conf.Timeout,
}
Run Code Online (Sandbox Code Playgroud)

如果conf.HostKey为空 - 它仍然可以工作 - 但会记录一条警告,其中包含要填写的密钥字符串以启用 SSH 密钥验证。