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))
}
|