forked from jackc/tern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh_tunnel.go
44 lines (36 loc) · 997 Bytes
/
ssh_tunnel.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
package main
import (
"fmt"
"net"
"os"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/knownhosts"
)
type SSHConnConfig struct {
Host string
Port string
User string
Password string
}
func NewSSHClient(config *SSHConnConfig) (*ssh.Client, error) {
sshConfig := &ssh.ClientConfig{
User: config.User,
Auth: []ssh.AuthMethod{SSHAgent()},
}
if config.Password != "" {
sshConfig.Auth = append(sshConfig.Auth, ssh.Password(config.Password))
}
if homeDir, err := os.UserHomeDir(); err == nil {
if hostKeyCallback, err := knownhosts.New(fmt.Sprintf("%s/.ssh/known_hosts", homeDir)); err == nil {
sshConfig.HostKeyCallback = hostKeyCallback
}
}
return ssh.Dial("tcp", net.JoinHostPort(config.Host, config.Port), sshConfig)
}
func SSHAgent() ssh.AuthMethod {
if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
return ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)
}
return nil
}