-
Notifications
You must be signed in to change notification settings - Fork 20
/
ssh.go
75 lines (66 loc) · 1.49 KB
/
ssh.go
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package webssh
import (
"io/ioutil"
"time"
"golang.org/x/crypto/ssh"
)
type AuthModel int8
const (
PASSWORD AuthModel = iota + 1
PUBLICKEY
)
type SSHClientConfig struct {
AuthModel AuthModel
HostAddr string
User string
Password string
KeyPath string
Timeout time.Duration
}
func SSHClientConfigPassword(hostAddr, user, Password string) *SSHClientConfig {
return &SSHClientConfig{
Timeout: time.Second * 5,
AuthModel: PASSWORD,
HostAddr: hostAddr,
User: user,
Password: Password,
}
}
func SSHClientConfigPulicKey(hostAddr, user, keyPath string) *SSHClientConfig {
return &SSHClientConfig{
Timeout: time.Second * 5,
AuthModel: PUBLICKEY,
HostAddr: hostAddr,
User: user,
KeyPath: keyPath,
}
}
func NewSSHClient(conf *SSHClientConfig) (*ssh.Client, error) {
config := &ssh.ClientConfig{
Timeout: conf.Timeout,
User: conf.User,
HostKeyCallback: ssh.InsecureIgnoreHostKey(), //忽略know_hosts检查
}
switch conf.AuthModel {
case PASSWORD:
config.Auth = []ssh.AuthMethod{ssh.Password(conf.Password)}
case PUBLICKEY:
signer, err := getKey(conf.KeyPath)
if err != nil {
return nil, err
}
config.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)}
}
c, err := ssh.Dial("tcp", conf.HostAddr, config)
if err != nil {
return nil, err
}
return c, nil
}
func getKey(keyPath string) (ssh.Signer, error) {
key, err := ioutil.ReadFile(keyPath)
if err != nil {
return nil, err
}
return ssh.ParsePrivateKey(key)
}