/
ssh.go
43 lines (35 loc) · 802 Bytes
/
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
package main
import (
"net"
"os"
"strings"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/knownhosts"
)
func sshClient(username, host string) (*ssh.Client, error) {
agentconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
return nil, err
}
aclient := agent.NewClient(agentconn)
callback, err := knownhosts.New(os.Getenv("HOME") + "/.ssh/known_hosts")
if err != nil {
callback = ssh.InsecureIgnoreHostKey()
}
conf := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeysCallback(aclient.Signers),
},
HostKeyCallback: callback,
}
if strings.Index(host, ":") < 0 {
host = host + ":22"
}
cli, err := ssh.Dial("tcp", host, conf)
if err != nil {
return nil, err
}
return cli, nil
}