Featured image of post Golang SSH远程:ssh: handshake failed: EOF

Golang SSH远程:ssh: handshake failed: EOF

** 初学Golang,打算用它写个服务器批量执行命令的程序,在远程ssh登录的时候出现了报错:ssh: handshake failed: EOF **

** 报错信息:**
ssh报错.png

** 演示代码 **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main

import (
	"fmt"
	"golang.org/x/crypto/ssh"
	"log"
	"time"
)

func main() {
	sshHost := "10.0.88.66"
	sshUser := "root"
	sshPassword := "123456"
	sshType := "password" //password 或者 key
	sshPort := 22

	////创建sshp登陆配置
	config := &ssh.ClientConfig{
		Timeout:         time.Second * 3,
		User:            sshUser,
		HostKeyCallback: ssh.InsecureIgnoreHostKey(), //这个可以, 但是不够安全
		//HostKeyCallback: hostKeyCallBackFunc(h.Host),
	}
	if sshType == "password" {

		config.Auth = []ssh.AuthMethod{ssh.Password(sshPassword)}
	}

	//dial 获取ssh client
	addr := fmt.Sprintf("%s:%d", sshHost, sshPort)
	sshClient, err := ssh.Dial("tcp", addr, config)
	if err != nil {
		log.Fatal("创建ssh client 失败", err)
	}
	defer sshClient.Close()

	//创建ssh-session
	session, err := sshClient.NewSession()
	if err != nil {
		log.Fatal("创建ssh session 失败", err)
	}
	defer session.Close()
	//执行远程命令
	combo, err := session.CombinedOutput("ls -lh")
	if err != nil {
		log.Fatal("远程执行cmd 失败", err)
	}
	log.Println("命令输出:", string(combo))
}

** 解决办法:**
ssh 虽然经常用,但协议层面我了解不多;出现这个问题的原因好像挺多的,如果你也遇到,可以尝试换个加密算法; 在配置里面更换一种算法,成功解决问题,希望能够帮到您。

1
config.Ciphers = append(config.Ciphers, "aes128-ctr")
本文采用 CC BY 4.0 协议,转载请署名并注明出处。
最后更新于 2021-07-12 15:40:34
使用 Hugo 构建
主题 StackJimmy 设计