-
Notifications
You must be signed in to change notification settings - Fork 47
/
scp.go
91 lines (75 loc) · 1.74 KB
/
scp.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
81
82
83
84
85
86
87
88
89
90
91
package scp
import (
"fmt"
"io/ioutil"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"github.com/kubermatic/cluster-api-provider-digitalocean/pkg/ssh"
"github.com/pkg/sftp"
)
// Client represents SCP client.
type Client struct {
client *ssh.Client
}
func NewSCPClient(sshClient *ssh.Client) *Client {
return &Client{
client: sshClient,
}
}
// ReadBytes reads from remote location.
func (cl *Client) ReadBytes(remotePath string) ([]byte, error) {
if cl.client.Conn == nil {
return nil, fmt.Errorf("connection not established")
}
c, err := sftp.NewClient(cl.client.Conn)
if err != nil {
return nil, err
}
defer func() {
if err := c.Close(); err != nil {
utilruntime.HandleError(fmt.Errorf("failed to close ssh connection: %v", err))
}
}()
r, err := c.Open(remotePath)
if err != nil {
return nil, err
}
defer func() {
if err := r.Close(); err != nil {
utilruntime.HandleError(fmt.Errorf("failed to close ssh connection: %v", err))
}
}()
bytes, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return bytes, nil
}
// WriteBytes writes to remote location.
func (cl *Client) WriteBytes(remotePath string, content []byte) error {
if cl.client.Conn == nil {
return fmt.Errorf("connection not established")
}
c, err := sftp.NewClient(cl.client.Conn)
if err != nil {
return err
}
defer func() {
if err := c.Close(); err != nil {
utilruntime.HandleError(fmt.Errorf("failed to close ssh connection: %v", err))
}
}()
f, err := c.Create(remotePath)
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
utilruntime.HandleError(fmt.Errorf("failed to close ssh connection: %v", err))
}
}()
_, err = f.Write(content)
if err != nil {
return err
}
return nil
}