This repository has been archived by the owner on Jan 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
ssh.go
128 lines (110 loc) · 2.41 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package sshclient
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"strings"
"golang.org/x/crypto/ssh"
)
type Client struct {
KeyPair *SSHKeyPair
}
type SSHKeyPair struct {
PrivateKey *rsa.PrivateKey
PublicKey ssh.PublicKey
PrivateKeyPEM []byte
AuthorizedKey []byte
}
func New() (*Client, error) {
ssh := &Client{}
err := ssh.generateKeyPair()
if err != nil {
return nil, err
}
return ssh, nil
}
func (s *Client) openSession(user, host string) (*ssh.Session, error) {
signer, err := ssh.NewSignerFromKey(s.KeyPair.PrivateKey)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: user,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
}
client, err := ssh.Dial("tcp", host+":22", config)
if err != nil {
return nil, err
}
session, err := client.NewSession()
if err != nil {
return nil, err
}
return session, nil
}
func (s *Client) GetFileFromContainer(user, host, containerName, file string) (string, error) {
command := fmt.Sprintf("docker exec %s cat %s", containerName, file)
return s.Run(user, host, command)
}
func (s *Client) Run(user, host, command string) (string, error) {
session, err := s.openSession(user, host)
if err != nil {
return "", err
}
rOut, err := session.StdoutPipe()
if err != nil {
return "", err
}
rErr, err := session.StderrPipe()
if err != nil {
return "", err
}
combined := io.MultiReader(rOut, rErr)
err = session.Start(command)
if err != nil {
return "", err
}
var lines []string
scanner := bufio.NewScanner(combined)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
session.Close()
output := strings.Join(lines, "\n")
output = strings.TrimSpace(output)
return output, nil
}
func (s *Client) generateKeyPair() error {
privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return err
}
var pembuf bytes.Buffer
err = pem.Encode(&pembuf, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
})
if err != nil {
return err
}
publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)
if err != nil {
return err
}
authorizedKey := ssh.MarshalAuthorizedKey(publicKey)
s.KeyPair = &SSHKeyPair{
PrivateKey: privateKey,
PublicKey: publicKey,
PrivateKeyPEM: pembuf.Bytes(),
AuthorizedKey: authorizedKey,
}
return nil
}