-
Notifications
You must be signed in to change notification settings - Fork 71
/
ssh_tunnel.go
62 lines (52 loc) · 1.37 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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,
}
if auth := SSHAgent(); auth != nil {
sshConfig.Auth = append(sshConfig.Auth, auth)
}
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
}
if auth := PrivateKey(fmt.Sprintf("%s/.ssh/id_rsa", homeDir)); auth != nil {
sshConfig.Auth = append(sshConfig.Auth, auth)
}
}
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
}
func PrivateKey(path string) ssh.AuthMethod {
key, err := os.ReadFile(path)
if err != nil {
return nil
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil
}
return ssh.PublicKeys(signer)
}