forked from taggledevel2/ratchet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sftp.go
61 lines (48 loc) · 1.3 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
package util
import (
"io/ioutil"
"path/filepath"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
// SftpParameters is used for storing connection parameters for later executing sftp commands
type SftpParameters struct {
Server string
Username string
Path string
AuthMethods []ssh.AuthMethod
}
// SftpPath is a simple struct for storing the full path of an object
type SftpPath struct {
Path string `json:"path,omitempty"`
}
// FileName defers to filepath.Base
func (t SftpPath) FileName() string {
return filepath.Base(t.Path)
}
// SftpClient sets up and return the client
func SftpClient(server string, username string, authMethod []ssh.AuthMethod, opts ...func(*sftp.Client) error) (*sftp.Client, error) {
var client *sftp.Client
config := &ssh.ClientConfig{
User: username,
Auth: authMethod,
}
conn, err := ssh.Dial("tcp", server, config)
if err != nil {
return client, err
}
return sftp.NewClient(conn, opts...)
}
// SftpKeyAuth generates an ssh.AuthMethod given the path of a private key
func SftpKeyAuth(privateKeyPath string) (auth ssh.AuthMethod, err error) {
privateKey, err := ioutil.ReadFile(privateKeyPath)
if err != nil {
return
}
signer, err := ssh.ParsePrivateKey([]byte(privateKey))
if err != nil {
return
}
auth = ssh.PublicKeys(signer)
return
}