forked from devfans/xssh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
462 lines (402 loc) · 10.6 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/coreos/etcd/client"
"github.com/devfans/envconf"
"golang.org/x/net/context"
)
// `host, hostname, user, bastion, category`
var (
// etcd store
pRoot *string = flag.String("root", "/ssh", "etcd root path")
pEndpoint *string = flag.String("url", "", "store endpoint")
// host operations
pAdd *bool = flag.Bool("add", false, "add host into store")
pGet *bool = flag.Bool("get", false, "get host details from store")
pList *bool = flag.Bool("list", false, "list hosts from store")
pChange *bool = flag.Bool("change", false, "change host parameters")
pDelete *bool = flag.Bool("del", false, "delete host from store")
pAwsInput *bool = flag.Bool("awsInput", false, "import from aws inventory file")
pSave *bool = flag.Bool("save", false, "save ssh config file to disk as ~/.ssh/config")
pStore *bool = flag.Bool("s", false, "save store configuration as ~/.ssh/store")
pFile *string = flag.String("file", "", "file path")
// key operations
pGetKey *bool = flag.Bool("getKey", false, "get key directory from store")
pListKeys *bool = flag.Bool("listKeys", false, "list keys from store")
pDelKey *bool = flag.Bool("delKey", false, "delete key from store")
pPutKey *bool = flag.Bool("putKey", false, "put key into store")
pKey *string = flag.String("key", "", "dir key in store")
pValue *string = flag.String("value", "", "specifiy key's value")
pAllKeys *bool = flag.Bool("allKeys", false, "get all keys from store recursively")
// host args
pHost *string = flag.String("host", "", "host: Host in ssh/config")
pRename *string = flag.String("rename", "", "new host name for changing host parameters")
pHostname *string = flag.String("ip", "", "ip or domain name: HostName in ssh/config")
pPort *string = flag.String("port", "22", "port: Port in ssh/config")
pUser *string = flag.String("user", "ubuntu", "username: User in ssh/config")
pBastion *string = flag.String("bastion", "", "bastion host: used for ProxyComand in ssh/config")
pCategory *string = flag.String("category", "default", "category")
pPem *string = flag.String("pem", "", "private key file name, default will be user.pem under ~/.ssh")
)
func checkError(err error) {
if err != nil {
panic(err)
}
}
func checkFatal(err error, tpl string, args ...interface{}) {
if err != nil {
fmt.Printf(tpl, args...)
panic(err)
}
}
// Store interface for key operations
type Store interface {
init()
GetKey(key string) (string, error)
DelKey(key string) error
ListKeys(recursive bool)
PutKey(key, value string) error
CollectKeys() [][]byte
}
// etcd store implementation
type EtcdStore struct {
client client.KeysAPI
}
// main config object
type Config struct {
store Store
}
// host model
type Host struct {
Host string
Ip string
Port string
Bastion string
User string
Category string
Dir string
Pem string
}
func (c *Config) init() {
// currently only support etcd store
c.store = &EtcdStore{}
c.store.init()
}
// create main config
func NewConfig() *Config {
config := &Config{}
config.init()
return config
}
func (es *EtcdStore) init() {
fmt.Printf("Using etcd store:%s\n", *pEndpoint)
cfg := client.Config{
Endpoints: []string{*pEndpoint},
Transport: client.DefaultTransport,
HeaderTimeoutPerRequest: time.Second,
}
c, err := client.New(cfg)
checkError(err)
es.client = client.NewKeysAPI(c)
}
// save host into store
func (h *Host) Save(store Store) bool {
h.GetDir()
jsonData, err := json.Marshal(h)
checkError(err)
err = store.PutKey(h.Dir, string(jsonData))
checkError(err)
return true
}
// delete host from store
func (h *Host) Del(store Store) {
h.GetDir()
err := store.DelKey(h.Dir)
checkError(err)
fmt.Printf("Deleted %v\n", h.Dir)
}
// dump host config to string
func (h *Host) String() string {
parts := []string{"Host " + h.Host,
"HostName " + h.Ip, "Port " + h.Port,
"User " + h.User, "IdentityFile " + h.Pem}
if len(h.Bastion) > 0 {
parts = append(parts, "ProxyCommand ssh "+h.Bastion+" -W "+"%%"+"h:"+"%%"+"p")
}
return fmt.Sprint(strings.Join(parts, "\n "))
}
// compose host key path
func (h *Host) GetDir() {
h.Dir = *pRoot + "/" + h.Category + "/" + h.Host
}
// get host from store
func (h *Host) Get(store Store) {
h.GetDir()
resp, err := store.GetKey(h.Dir)
checkError(err)
fmt.Printf("Fetching...\n%v", resp)
err = json.Unmarshal([]byte(resp), h)
checkError(err)
}
// get key from etcd store
func (es *EtcdStore) GetKey(key string) (string, error) {
resp, err := es.client.Get(context.Background(), key, nil)
if err != nil {
return "", err
} else {
return fmt.Sprint(resp.Node.Value), nil
}
}
func printNodeKeys(node *client.Node) {
if node == nil {
return
}
fmt.Println(node.Key)
for i := range node.Nodes {
printNodeKeys(node.Nodes[i])
}
}
// list keys from etcd store
func (es *EtcdStore) ListKeys(recursive bool) {
resp, err := es.client.Get(context.Background(), *pKey, &client.GetOptions{Recursive: recursive})
checkError(err)
printNodeKeys(resp.Node)
}
// put key into etcd store
func (es *EtcdStore) PutKey(key, value string) error {
_, err := es.client.Set(context.Background(), key, value, nil)
if err == nil {
fmt.Printf("Set is done for key: %v with value %v\n", key, value)
}
return err
}
// delete key from etcd store
func (es *EtcdStore) DelKey(key string) error {
_, err := es.client.Delete(context.Background(), key, nil)
return err
}
// collect host keys from store
func (es *EtcdStore) CollectKeys() [][]byte {
keys := make([][]byte, 0)
*pKey = "/ssh"
resp, err := es.client.Get(context.Background(), *pKey,
&client.GetOptions{Recursive: true})
checkError(err)
for _, node := range resp.Node.Nodes {
for _, cnode := range node.Nodes {
keys = append(keys, []byte(cnode.Value))
}
}
return keys
}
// collect hosts from store
func (c *Config) CollectHosts() []Host {
var hosts []Host
keys := c.store.CollectKeys()
for _, key := range keys {
host := Host{}
err := json.Unmarshal(key, &host)
checkError(err)
hosts = append(hosts, host)
}
return hosts
}
// list all hosts
func (c *Config) ListHosts() {
hosts := c.CollectHosts()
for _, h := range hosts {
fmt.Println(h.String() + "\n")
}
}
// save as file: ~/.ssh/config
func (c *Config) Save() {
hosts := c.CollectHosts()
configDir, err := filepath.Abs(os.Getenv("HOME") + "/.ssh/config")
checkError(err)
_, err = os.Stat(configDir)
checkError(err)
err = os.Rename(configDir, configDir+string(time.Now().Format(time.RFC3339)))
checkError(err)
f, err := os.OpenFile(configDir, os.O_RDWR|os.O_CREATE, 0755)
checkError(err)
defer f.Close()
for _, h := range hosts {
fmt.Printf("Writing host %v\n", h.Host)
_, err = f.WriteString(h.String() + "\n")
checkError(err)
}
fmt.Printf("Config file save as %v\n", configDir)
}
// import host from aws inventory file
func (c *Config) AwsImport() {
if len(*pFile) == 0 {
panic("Please specify the file!")
}
fileDir, err := filepath.Abs(*pFile)
checkError(err)
fmt.Printf("Loading from: %v\n", fileDir)
f, err := os.Open(fileDir)
checkError(err)
defer f.Close()
var j interface{}
jsonParser := json.NewDecoder(f)
err = jsonParser.Decode(&j)
checkError(err)
d := j.(map[string]interface{})
meta := d["_meta"].(map[string]interface{})
items := meta["hostvars"].(map[string]interface{})
for k, v := range items {
_ = v.(map[string]interface{})
fmt.Printf("adding %v\n", k)
h := Host{Host: k, Ip: k, User: *pUser, Port: *pPort, Bastion: *pBastion, Category: *pCategory}
h.GetDir()
jsonData, err := json.Marshal(h)
checkError(err)
err = c.store.PutKey(h.Dir, string(jsonData))
checkError(err)
}
}
// add host into store
func (c *Config) AddHost() {
if len(*pHost) == 0 {
panic("HostName is missing!")
}
if len(*pPem) == 0 {
var err error
*pPem, err = filepath.Abs(os.Getenv("HOME") + "/.ssh/id_rsa")
checkError(err)
}
h := Host{
Host: *pHost,
Ip: *pHostname,
Port: *pPort,
User: *pUser,
Bastion: *pBastion,
Category: *pCategory,
Pem: *pPem,
}
if h.Save(c.store) {
fmt.Printf("Host %v added\n", *pHost)
} else {
fmt.Printf("Failed to add host %v\n", *pHost)
}
}
// get host from store
func (c *Config) GetHost() {
if len(*pHost) == 0 {
panic("HostName is missing!")
}
h := Host{Host: *pHost, Category: *pCategory}
h.Get(c.store)
fmt.Println(h.String() + "\n")
}
// change host config
func (c *Config) ChangeHost() {
if len(*pHost) == 0 {
panic("HostName is missing!")
}
h := Host{Host: *pHost, Category: *pCategory}
h.Get(c.store)
if len(*pRename) != 0 {
h.Host = *pRename
}
if len(*pUser) != 0 {
h.User = *pUser
}
if len(*pHostname) != 0 {
h.Ip = *pHostname
}
if *pPort != "22" {
h.Port = *pPort
}
if len(*pBastion) != 0 {
h.Bastion = *pBastion
} else {
h.Bastion = ""
}
if h.Save(c.store) {
h.Host = *pHost
if len(*pRename) != 0 {
h.Del(c.store)
fmt.Printf("Host name changed from %v to %v\n", *pHost, *pRename)
} else {
fmt.Printf("Host %s is modified\n", *pHost)
}
h.Get(c.store)
fmt.Println(h.String() + "\n")
}
}
// delete host
func (c *Config) DeleteHost() {
if len(*pHost) == 0 {
panic("HostName is missing!")
}
h := Host{Host: *pHost, Category: *pCategory}
h.Del(c.store)
fmt.Printf("Deleted %v\n", h.Dir)
}
func checkKey() {
if len(*pKey) == 0 {
panic(fmt.Sprintf("invalid key %v", *pKey))
}
}
func main() {
flag.Parse()
// get url from ~/.ssh/store or env: XSSH_STORE_URL
conf := envconf.NewConfig("~/.ssh/store")
conf.Put("store", "etcd")
conf.Section = "etcd"
if *pEndpoint == "" {
*pEndpoint = conf.Get("XSSH_ETCD_URL", "url")
}
if *pEndpoint == "" {
*pEndpoint = "http://localhost:2379"
}
conf.Put("url", *pEndpoint)
config := NewConfig()
if *pStore {
conf.Save()
} else if *pAdd {
config.AddHost()
} else if *pDelete {
config.DeleteHost()
} else if *pGet {
config.GetHost()
} else if *pSave {
config.Save()
} else if *pChange {
config.ChangeHost()
} else if *pList {
config.ListHosts()
} else if *pAllKeys {
config.store.ListKeys(true)
} else if *pGetKey {
checkKey()
v, err := config.store.GetKey(*pKey)
checkError(err)
fmt.Printf("value is: %v\n", v)
} else if *pPutKey {
checkKey()
err := config.store.PutKey(*pKey, *pValue)
checkError(err)
fmt.Printf("key %v is now set as %v\n", *pKey, *pValue)
} else if *pListKeys {
checkKey()
config.store.ListKeys(false)
} else if *pDelKey {
checkKey()
err := config.store.DelKey(*pKey)
checkError(err)
fmt.Printf("key %v is removed\n", *pKey)
} else if *pAwsInput {
config.AwsImport()
} else {
panic("Invalid parameters set!")
}
}