-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
249 lines (210 loc) · 5.66 KB
/
main.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package gohpygossh
/*
Main based on
https://gist.github.com/iamralch/b7f56afc966a6b6ac2fc
*/
import (
"bytes"
"crypto/rand"
"encoding/base64"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
func Hello() string {
return "Hello, world"
}
type KeysForSsh struct {
CloudUser string
PrivKeyAbsPath string
PublicKeyAbsPath string
Err string
}
func GenerateKeysForSsh(destinationDir string, cloudUser string) KeysForSsh {
// Generate a new SSH key pair
fmt.Printf("Generating keypair for user: %s", cloudUser)
temp_file, err := os.CreateTemp(destinationDir, "id_rsa_test")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
privateKeyFileName := temp_file.Name()
cmd := fmt.Sprintf("ssh-keygen -b 2048 -t rsa -q -N '' -f " + privateKeyFileName + " <<<y >/dev/null 2>&1")
output, exec_cmd_err := exec.Command("bash", "-c", cmd).Output()
if exec_cmd_err != nil {
fmt.Println(exec_cmd_err)
os.Exit(1)
}
fmt.Println(output)
publicKeyAbsPath, err := filepath.Abs("" + privateKeyFileName + ".pub")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
privateKeyAbsPath, err := filepath.Abs(privateKeyFileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return KeysForSsh{
CloudUser: cloudUser,
PublicKeyAbsPath: publicKeyAbsPath,
PrivKeyAbsPath: privateKeyAbsPath,
Err: fmt.Sprint(err),
}
}
type KeysAndInit struct {
CloudInitPath string
SshKeyPath string
CloudUser string
Err string
}
func GenerateKeyPairAndCloudInit(destinationDir string, cloudUser string) KeysAndInit {
// Generate a new SSH key pair
fmt.Printf("Generating keypair & cloud-init for user: %s", cloudUser)
temp_file, err := os.CreateTemp(destinationDir, "id_rsa_test")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
privateKeyFileName := temp_file.Name()
cmd := fmt.Sprintf("ssh-keygen -b 2048 -t rsa -q -N '' -f " + privateKeyFileName + " <<<y >/dev/null 2>&1")
output, exec_cmd_err := exec.Command("bash", "-c", cmd).Output()
if exec_cmd_err != nil {
fmt.Println(exec_cmd_err)
os.Exit(1)
}
fmt.Println(output)
// Get the public SSH key (file content)
publicKey, err := os.ReadFile("" + privateKeyFileName + ".pub")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Create a new cloud-init file
cloud_init_file_path := fmt.Sprintf("%s/cloud-init.yaml", destinationDir)
cloudInitFile, err := os.Create(cloud_init_file_path)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Write the cloud-init file
cloudInitFile.WriteString(`
users:
- name: ` + cloudUser + `
groups: users, admin
sudo: ALL=(ALL) NOPASSWD:ALL
ssh_authorized_keys:
- ` + strings.TrimSpace(string(publicKey)) + `
`)
defer cloudInitFile.Close()
cloud_init_abs_path, err := filepath.Abs(cloudInitFile.Name())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// publicKeyAbsPath, err := filepath.Abs("" + privateKeyFileName + ".pub")
privateKeyAbsPath, err := filepath.Abs(privateKeyFileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(privateKeyAbsPath)
// return cloud_init_abs_path, privateKeyAbsPath, err
return KeysAndInit{
CloudInitPath: cloud_init_abs_path,
SshKeyPath: privateKeyAbsPath,
CloudUser: cloudUser,
Err: fmt.Sprint(err),
}
}
func GenerateShortUUID(length int) (string, error) {
// Generate random bytes
randomBytes := make([]byte, length/3*4) // Adjust for base64 encoding
_, err := rand.Read(randomBytes)
if err != nil {
return "", err
}
// Base64 encode without padding
encodedString := base64.RawURLEncoding.EncodeToString(randomBytes)
// Truncate to desired length and remove trailing '=' padding
return encodedString[:length], nil
}
func PublicKeyFile(file string) ssh.AuthMethod {
f, err := os.Open(file)
if err != nil {
return nil
}
defer f.Close()
// Chunk size
const maxSize = 4
// Create buffer
byteBuffer := make([]byte, maxSize)
key, err := ssh.ParsePrivateKey(byteBuffer)
if err != nil {
return nil
}
return ssh.PublicKeys(key)
}
func Run(hostname string, username string, privateKey string, command string) (string, error) {
// envVars map[string]string) string {
// Establish an SSH connection to the remote server
// key1, err := ssh.ParsePrivateKey([]byte(privateKey))
keyBytes, err := os.ReadFile(privateKey)
if err != nil {
return "", err
}
signer, err := ssh.ParsePrivateKey(keyBytes)
if err != nil {
return "", err
}
// signer, err := ssh.ParseRawPrivateKey([]byte(privateKey))
// key, err := x509.ParsePKCS1PrivateKey([]byte(privateKey))
// if err != nil {
// log.Fatal(err)
// }
// signer, err := ssh.NewSignerFromKey(key)
// ssh.PublicKeys(key),
// ssh.PublicKeys(key),
// ssh.ParseRawPrivateKey(privateKey),
if err != nil {
return "", err
}
sshConfig := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
/*
FIXME: Work on supporting host key verification.
See: https://stackoverflow.com/a/63308243
*/
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
// Env: envVars,
// env: envVars,
Timeout: time.Duration(time.Duration.Seconds(60)),
}
client, err := ssh.Dial("tcp", net.JoinHostPort(hostname, "22"), sshConfig)
if err != nil {
return "", err
}
// Create a session. It is one session per command.
session, err := client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
var b bytes.Buffer // import "bytes"
session.Stdout = &b // get output
// you can also pass what gets input to the stdin, allowing you to pipe
// content from client to server
// session.Stdin = bytes.NewBufferString("My input")
// Finally, run the command
err = session.Run(command)
return b.String(), err
}