-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsftp.go
80 lines (72 loc) · 1.68 KB
/
sftp.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
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
kh "golang.org/x/crypto/ssh/knownhosts"
)
func getKnownHostsFile(providedPath string) string {
if providedPath != "" {
return providedPath
}
dirname, err := os.UserHomeDir()
if err == nil {
return filepath.Join(dirname, ".ssh/known_hosts")
} else {
return ""
}
}
var hostKeyCallback *ssh.HostKeyCallback
var signer *ssh.Signer
func createSftpClient(config *DirFsConfig) (*sftp.Client, error) {
var err error
if hostKeyCallback == nil {
hostKeyCallbackImpl, err := kh.New(getKnownHostsFile(config.KnownHosts))
if err != nil {
return nil, err
}
hostKeyCallback = &hostKeyCallbackImpl
}
privateKey, err := ioutil.ReadFile(config.IdentityFile)
if err != nil {
log.Fatalf("can't load identity file: %v", err)
}
if signer == nil {
var signerImpl ssh.Signer
secret := config.Password
// Create the Signer for this private key.
if secret == "" {
signerImpl, err = ssh.ParsePrivateKey(privateKey)
} else {
signerImpl, err = ssh.ParsePrivateKeyWithPassphrase(privateKey, []byte(secret))
}
if err != nil {
return nil, err
}
signer = &signerImpl
}
sshClient := &ssh.ClientConfig{
User: config.Username,
Auth: []ssh.AuthMethod{
// Add in password check here for moar security.
ssh.PublicKeys(*signer),
},
HostKeyCallback: *hostKeyCallback,
Timeout: 10 * time.Second,
}
// Dial your ssh server.
conn, err := ssh.Dial("tcp", config.Host+":"+fmt.Sprint(config.Port), sshClient)
if err != nil {
return nil, err
}
client, err := sftp.NewClient(conn)
if err != nil {
return nil, err
}
return client, nil
}