-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
112 lines (96 loc) · 2.34 KB
/
config.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package rcom
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
var Logger = log.New(ioutil.Discard, "", 0)
type Config struct {
acceptNew bool // acceptNew entries to known_hosts
port int
knownHosts string
identityAuth ssh.AuthMethod
passwordAuth ssh.AuthMethod
clientConfig ssh.ClientConfig
}
type ConfigOption func(*Config) error
func Login(username string) ConfigOption {
return func(config *Config) error {
config.clientConfig.User = username
return nil
}
}
func Port(port int) ConfigOption {
return func(config *Config) error {
if port < 1 || 65535 < port {
return fmt.Errorf("Setting destination port failed: Valid port values are 1-65535")
}
config.port = port
return nil
}
}
func Accept(accept bool) ConfigOption {
return func(config *Config) error {
config.acceptNew = accept
return nil
}
}
func KnownHosts(file string) ConfigOption {
return func(config *Config) error {
config.knownHosts = file
return nil
}
}
func IdentityFile(file string) ConfigOption {
return func(config *Config) error {
if file == "" {
return nil
}
if _, err := os.Stat(file); os.IsNotExist(err) {
return fmt.Errorf("No such identity file: %s", file)
} else if err != nil {
return err
}
key, err := ioutil.ReadFile(file)
if err != nil {
return fmt.Errorf("Failed to read identity file %s: %v", file, err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return fmt.Errorf("Failed to parse private key %s: %v", file, err)
}
config.identityAuth = ssh.PublicKeys(signer)
return nil
}
}
func DefaultIdentityFile(homedir string) ConfigOption {
return func(config *Config) error {
for _, f := range []string{"id_dsa_rcom", "id_ecdsa_rcom", "id_ed25519_rcom", "id_rsa_rcom"} {
f = filepath.Join(homedir, ".ssh", f)
if _, err := os.Stat(f); err == nil {
return IdentityFile(f)(config)
}
}
return fmt.Errorf("No identify file found in %s", homedir)
}
}
type readWriter struct {
io.Reader
io.Writer
}
func PasswordAuth() ConfigOption {
return func(config *Config) error {
config.passwordAuth = ssh.PasswordCallback(func() (string, error) {
fmt.Fprintf(os.Stdout, "Password: ")
pass, err := terminal.ReadPassword(0)
fmt.Fprintf(os.Stdout, "\n")
return string(pass), err
})
return nil
}
}