ssh/config.go

99 lines
1.9 KiB
Go
Raw Permalink Normal View History

2018-10-30 17:45:30 +08:00
package ssh
import (
2018-11-13 17:42:29 +08:00
"os"
"path"
2018-10-30 17:45:30 +08:00
"time"
)
type Config struct {
2018-11-06 15:37:35 +08:00
User string
Host string
Port int
Password string
KeyFiles []string
Passphrase string
2018-10-30 17:45:30 +08:00
2018-11-06 15:37:35 +08:00
StickySession bool
2018-10-30 17:45:30 +08:00
// DisableAgentForwarding, if true, will not forward the SSH agent.
DisableAgentForwarding bool
// HandshakeTimeout limits the amount of time we'll wait to handshake before
// saying the connection failed.
HandshakeTimeout time.Duration
// KeepAliveInterval sets how often we send a channel request to the
// server. A value < 0 disables.
KeepAliveInterval time.Duration
// Timeout is how long to wait for a read or write to succeed.
Timeout time.Duration
}
var DefaultConfig = &Config{
2018-11-13 17:42:29 +08:00
Host: "localhost",
Port: 22,
User: "root",
// KeyFiles: []string{path.Join(os.Getenv("HOME"), "/.ssh/id_rsa")},
2018-10-30 17:45:30 +08:00
}
2018-11-13 17:42:29 +08:00
var Default = DefaultConfig
2018-10-30 17:45:30 +08:00
2018-11-13 17:42:29 +08:00
func WithUser(user string) *Config {
return Default.WithUser(user)
}
func (c *Config) WithUser(user string) *Config {
2018-10-30 17:45:30 +08:00
if user == "" {
user = "root"
}
c.User = user
return c
}
2018-11-13 17:42:29 +08:00
func WithHost(host string) *Config {
return Default.WithHost(host)
}
2018-10-30 17:45:30 +08:00
2018-11-13 17:42:29 +08:00
func (c *Config) WithHost(host string) *Config {
2018-10-30 17:45:30 +08:00
if host == "" {
host = "localhost"
}
c.Host = host
return c
}
2018-11-13 17:42:29 +08:00
func WithPassword(password string) *Config {
return Default.WithPassword(password)
}
func (c *Config) WithPassword(password string) *Config {
2018-10-30 17:45:30 +08:00
c.Password = password
return c
}
2018-11-13 17:42:29 +08:00
func WithKey(keyfile, passphrase string) *Config {
return Default.WithKey(keyfile, passphrase)
2018-10-30 17:45:30 +08:00
}
2018-11-13 17:42:29 +08:00
func (c *Config) WithKey(keyfile, passphrase string) *Config {
2018-10-30 17:45:30 +08:00
if keyfile == "" {
2018-11-13 17:42:29 +08:00
if home := os.Getenv("HOME"); home != "" {
keyfile = path.Join(home, "/.ssh/id_rsa")
}
2018-10-30 17:45:30 +08:00
}
for _, s := range c.KeyFiles {
if s == keyfile {
return c
}
}
c.KeyFiles = append(c.KeyFiles, keyfile)
return c
}
2018-11-13 17:42:29 +08:00
//
func (c *Config) SetKeys(keyfiles []string) *Config {
if keyfiles == nil {
return c
}
t := make([]string, len(keyfiles))
copy(t, keyfiles)
c.KeyFiles = t
return c
}