/
client.go
88 lines (79 loc) · 2.24 KB
/
client.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
76
77
78
79
80
81
82
83
84
85
86
87
88
package client
import (
"io/ioutil"
"net"
"strconv"
"github.com/z1son/leap/config"
"golang.org/x/crypto/ssh"
)
// 用户名密码
func DialWithPasswd(auth *config.AllConfig) (*ssh.Client, error) {
config := &ssh.ClientConfig{
User: auth.Username,
Auth: []ssh.AuthMethod{
ssh.Password(auth.Password),
ssh.KeyboardInteractive(keyboardInteractivePassword(auth.GoogleAuthToken)),
},
HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
}
return ssh.Dial("tcp", auth.Address+":"+strconv.Itoa(auth.Port), config)
}
// 通过key文件
func DialWithKey(auth *config.AllConfig) (*ssh.Client, error) {
key, err := ioutil.ReadFile(auth.KeyFile)
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: auth.Username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
ssh.KeyboardInteractive(keyboardInteractivePassword(auth.GoogleAuthToken)),
},
HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
}
return ssh.Dial("tcp", auth.Address+":"+strconv.Itoa(auth.Port), config)
}
// key+password
func DialWithKeyAndPassword(auth *config.AllConfig) (*ssh.Client, error) {
key, err := ioutil.ReadFile(auth.KeyFile)
passwordBytes := []byte(auth.Password)
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKeyWithPassphrase(key, passwordBytes)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: auth.Username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
ssh.KeyboardInteractive(keyboardInteractivePassword(auth.GoogleAuthToken)),
},
HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
}
return ssh.Dial("tcp", auth.Address+":"+strconv.Itoa(auth.Port), config)
}
func GetClient(host config.AllConfig) (*ssh.Client, error) {
var (
cli *ssh.Client
err error
)
switch type_ := host.Type; type_ {
case "host":
cli, err = DialWithPasswd(&host)
case "key":
cli, err = DialWithKey(&host)
case "keyWithPass":
cli, err = DialWithKeyAndPassword(&host)
default:
cli = nil
err = nil
}
return cli, err
}