我使用 crypto/ssh
包生成了 SSH RSA key 对。但是,当我尝试通过 Go 中的脚本使用它时,我收到错误:
unable to connect: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain
当我通过 CLI 连接到远程设备时,它连接成功:
ssh -i ~/.ssh/test_key_1 <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b3b5a3b4a8a7aba386f7f1f4e8f4f4e8f2e8f7" rel="noreferrer noopener nofollow">[email protected]</a>
我是否可能错误地使用了该软件包?
注意:私钥没有密码。
package main
import (
"golang.org/x/crypto/ssh"
"io/ioutil"
"log"
)
func main() {
privateKeyFile := "/Users/username/.ssh/test_key_1"
remoteIP := "172.22.4.1:22"
user := "username"
privateKeyBytes, err := ioutil.ReadFile(privateKeyFile)
if err != nil {
log.Fatal(err)
}
key, err := ssh.ParsePrivateKey(privateKeyBytes)
if err != nil {
log.Fatal(err)
}
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
// Use the PublicKeys method for remote authentication.
ssh.PublicKeys(key),
},
// using InsecureIgnoreHostKey() for testing purposes
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", remoteIP, config)
if err != nil {
log.Fatalf("unable to connect: %v", err)
}
defer client.Close()
fmt.Println("Success!")
}
最佳答案
经过漫长的组件隔离过程后,我终于能够验证为什么我的 key 对无法进行身份验证。这是由于我使用的自定义便利包生成的公钥略有偏差。
我已经发布了他的一个未决问题:
https://github.com/ianmcmahon/encoding_ssh/issues/1
简而言之:
使用 EncodePublicKey()
函数创建的公钥如下:(为简洁起见,已截断)
ssh-rsa AAAAB3NzaC1yc2EAAAAEAAEAAQAAAgC2u3I/nbN9jcWDV..
但是,当运行ssh-keygen -y -f id_rsa
时,会创建以下内容:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC2u3I/nbN9jcWDV...
请注意粗体部分略有不同。这会导致 SSH 身份验证不起作用。
关于Go SSH key 不能与 crypto/ssh 一起使用,但可以手动使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47402775/