-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh.go
99 lines (81 loc) · 2.31 KB
/
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
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
92
93
94
95
96
97
98
99
package ggprov
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"time"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
// SSHSession state for the ssh session
type SSHSession struct {
Client *ssh.Client
}
// NewSSHSession create an ssh session
func NewSSHSession(hostname, port, username, keyPath string) (*SSHSession, error) {
log.Println("Loading key from path", keyPath)
key, err := ioutil.ReadFile(keyPath)
if err != nil {
return nil, errors.Wrap(err, "Failed to read key file")
}
// Create the Signer for this private key.
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, errors.Wrap(err, "Failed to parse private key")
}
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
Timeout: 30 * time.Second,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
log.Println("Connecting to host", hostname)
// Connect to the remote server and perform the SSH handshake.
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", hostname, port), config)
if err != nil {
return nil, errors.Wrap(err, "Failed to connect")
}
return &SSHSession{Client: client}, nil
}
// Copy copy a file with the supplied name, mode and contents
func (ss *SSHSession) Copy(size int64, mode os.FileMode, fileName string, contents io.Reader, destinationPath string) error {
return ss.copy(size, mode, fileName, contents, destinationPath)
}
// CopyPath copy a file
func (ss *SSHSession) CopyPath(filePath, destinationPath string) error {
log.Println("CopyPath to host", filePath, destinationPath)
f, err := os.Open(filePath)
if err != nil {
return err
}
defer DoClose(f)
s, err := f.Stat()
if err != nil {
return err
}
return ss.copy(s.Size(), s.Mode().Perm(), path.Base(filePath), f, destinationPath)
}
func (ss *SSHSession) copy(size int64, mode os.FileMode, fileName string, contents io.Reader, destination string) error {
session, err := ss.Client.NewSession()
if err != nil {
return errors.Wrap(err, "Failed to create session for copy")
}
defer DoClose(session)
go func() {
w, _ := session.StdinPipe()
defer DoClose(w)
fmt.Fprintf(w, "C%#o %d %s\n", mode, size, fileName)
_, err = io.Copy(w, contents)
if err != nil {
return
}
fmt.Fprint(w, "\x00")
}()
cmd := fmt.Sprintf("scp -t %s", destination)
return session.Run(cmd)
}