-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathssh.go
62 lines (49 loc) · 1.15 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
package avcli
import (
"fmt"
"io/ioutil"
"os"
"time"
"golang.org/x/crypto/ssh"
)
var (
defaultKeys = [...]string{"$HOME/.ssh/id_rsa"}
)
// NewSSHClient .
func NewSSHClient(address string) (*ssh.Client, error) {
label := fmt.Sprintf("%s's password", address)
sshConfig := &ssh.ClientConfig{
User: "pi",
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Auth: []ssh.AuthMethod{
ssh.PublicKeysCallback(getSigners),
ssh.RetryableAuthMethod(ssh.PasswordCallback(getPasswordFunc(label, 3)), 3),
},
Timeout: 2 * time.Second,
}
return ssh.Dial("tcp", address+":22", sshConfig)
}
func getSigners() ([]ssh.Signer, error) {
var signers []ssh.Signer
for _, path := range defaultKeys {
bytes, err := ioutil.ReadFile(path)
if err != nil {
continue
}
key, err := ssh.ParsePrivateKey(bytes)
if err != nil {
continue
}
signers = append(signers, key)
}
return signers, nil
}
func getPasswordFunc(label string, maxTries int) func() (string, error) {
return func() (string, error) {
password := os.Getenv("PI_PASSWORD")
if len(password) == 0 {
return "", fmt.Errorf("PI_PASSWORD not set")
}
return password, nil
}
}