我尝试使用 SSH 和 Go 连接到我的一台虚拟机。 如果我这样做,它可以通过命令行完美运行:
ssh root@my_host
我输入密码,一切正常。 我尝试在 Go 中执行此操作,这是我的代码:
package main
import (
"golang.org/x/crypto/ssh"
"fmt"
)
func connectViaSsh(user, host string, password string) (*ssh.Client, *ssh.Session) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(password)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", host, config)
fmt.Println(err)
session, err := client.NewSession()
fmt.Println(err)
return client, session
}
func main() {
client, _ := connectViaSsh("root", "host:22", "password")
client.Close()
}
如果我运行它,它会返回一个错误:
ssh: handshake failed: ssh: unable to authenticate, attempted methods [none], no supported methods remain
有没有人知道什么可能导致这样的错误。在 Python 和 shell 中使用 paramiko 可以正常工作,但在 Go 中失败。我有什么遗漏吗?
最佳答案
正如@JimB 和@putu 所指出的,我的服务器没有启用密码验证。
为了验证我是否使用详细选项运行 ssh,它会返回所有支持的身份验证方法。 就我而言,结果如下:
debug1 : Authentications that can continue: publickey,keyboard-interactive,hostbased
所以我有两个选择,要么在服务器上启用密码身份验证,要么使用其他方法进行身份验证。
要启用密码验证,请连接到您的服务器并打开 sshd 配置文件,如下所示:
vi /etc/ssh/sshd_config
查找行:PasswordAuthentication no
改为yes,保存更改并重启sshd服务:service ssh restart
之后,密码验证方法开始按预期工作。
也可以使用其他方法,我决定尝试键盘交互,用户通常使用 ssh 通过终端连接。
这是执行此操作的代码片段,在远程服务器询问密码问题后发送密码:
package main
import (
"bytes"
"golang.org/x/crypto/ssh"
"fmt"
)
func connectViaSsh(user, host string, password string) (*ssh.Client, *ssh.Session) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.KeyboardInteractive(SshInteractive),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", host, config)
fmt.Println(err)
session, err := client.NewSession()
fmt.Println(err)
return client, session
}
func SshInteractive(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
answers = make([]string, len(questions))
// The second parameter is unused
for n, _ := range questions {
answers[n] = "your_password"
}
return answers, nil
}
func main() {
var b bytes.Buffer
client, session := connectViaSsh("root", "host:22", "password")
session.Stdout = &b
session.Run("ls")
fmt.Println(b.String())
client.Close()
}
在我的例子中,服务器只问一个问题,即密码,如果你的服务器问的比这个多,你就需要建立一个完整的答案链来反馈。
关于go - Go : unable to authenticate, 中的 SSH 尝试了方法 [无],没有支持的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47102080/