forked from scottdware/go-junos
-
Notifications
You must be signed in to change notification settings - Fork 1
/
junos.go
852 lines (712 loc) · 23.4 KB
/
junos.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
// Package junos provides automation for Junos (Juniper Networks) devices, as
// well as interaction with Junos Space.
package junos
import (
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"net"
"regexp"
"strings"
"time"
"golang.org/x/crypto/ssh"
"github.com/Juniper/go-netconf/netconf"
)
// All of our RPC calls we use.
var (
rpcCommand = "<command format=\"text\">%s</command>"
rpcCommandXML = "<command format=\"xml\">%s</command>"
rpcCommandJSON = "<command format=\"json\">%s</command>"
rpcCommit = "<commit-configuration/>"
rpcCommitAt = "<commit-configuration><at-time>%s</at-time></commit-configuration>"
rpcCommitAtLog = "<commit-configuration><at-time>%s</at-time><log>%s</log></commit-configuration>"
rpcCommitCheck = "<commit-configuration><check/></commit-configuration>"
rpcCommitConfirm = "<commit-configuration><confirmed/><confirm-timeout>%d</confirm-timeout></commit-configuration>"
rpcCommitFull = "<commit-configuration><full/></commit-configuration>"
rpcFactsRE = "<get-route-engine-information/>"
rpcFactsChassis = "<get-chassis-inventory/>"
rpcConfigFileSet = "<load-configuration action=\"set\" format=\"text\"><configuration-set>%s</configuration-set></load-configuration>"
rpcConfigFileText = "<load-configuration format=\"text\"><configuration-text>%s</configuration-text></load-configuration>"
rpcConfigFileXML = "<load-configuration format=\"xml\"><configuration>%s</configuration></load-configuration>"
rpcConfigURLSet = "<load-configuration action=\"set\" format=\"text\" url=\"%s\"/>"
rpcConfigURLText = "<load-configuration format=\"text\" url=\"%s\"/>"
rpcConfigURLXML = "<load-configuration format=\"xml\" url=\"%s\"/>"
rpcConfigStringSet = "<load-configuration action=\"set\" format=\"text\"><configuration-set>%s</configuration-set></load-configuration>"
rpcConfigStringText = "<load-configuration action=\"replace\" format=\"text\"><configuration-text>%s</configuration-text></load-configuration>"
rpcConfigStringXML = "<load-configuration format=\"xml\"><configuration>%s</configuration></load-configuration>"
rpcGetRescue = "<get-rescue-information><format>text</format></get-rescue-information>"
rpcGetRollback = "<get-rollback-information><rollback>%d</rollback><format>text</format></get-rollback-information>"
rpcGetRollbackCompare = "<get-rollback-information><rollback>0</rollback><compare>%d</compare><format>text</format></get-rollback-information>"
rpcGetCandidateCompare = "<get-configuration compare=\"rollback\" rollback=\"%d\" format=\"text\"/>"
rpcHardware = "<get-chassis-inventory/>"
rpcLock = "<lock-configuration/>"
rpcRescueConfig = "<load-configuration rescue=\"rescue\"/>"
rpcRescueDelete = "<request-delete-rescue-configuration/>"
rpcRescueSave = "<request-save-rescue-configuration/>"
rpcRollbackConfig = "<load-configuration rollback=\"%d\"/>"
rpcRoute = "<get-route-engine-information/>"
rpcSoftware = "<get-software-information/>"
rpcUnlock = "<unlock-configuration/>"
rpcVersion = "<get-software-information/>"
rpcReboot = "<request-reboot/>"
rpcCommitHistory = "<get-commit-information/>"
rpcFileList = "<file-list><detail/><path>%s</path></file-list>"
rpcInterfaces = "<get-interface-information/>"
)
// Junos contains our session state.
type Junos struct {
Session *netconf.Session
Hostname string
RoutingEngines int
Platform []RoutingEngine
CommitTimeout time.Duration
}
// AuthMethod defines how we want to authenticate to the device. If using a
// username and password to authenticate, the Credentials field must be populated like so:
//
// []string{"user", "password"}
//
// If you are using an SSH prviate key for authentication, you must provide the username,
// path to the private key, and passphrase. On most systems, the private key is found in
// the following location:
//
// ~/.ssh/id_rsa
//
// If you do not have a passphrase tied to your private key, then you can omit this field.
type AuthMethod struct {
Credentials []string
Username string
PrivateKey string
Passphrase string
}
// CommitHistory holds all of the commit entries.
type CommitHistory struct {
Entries []CommitEntry `xml:"commit-history"`
}
// CommitEntry holds information about each prevous commit.
type CommitEntry struct {
Sequence int `xml:"sequence-number"`
User string `xml:"user"`
Method string `xml:"client"`
Log string `xml:"log"`
Comment string `xml:"comment"`
Timestamp string `xml:"date-time"`
}
// RoutingEngine contains the hardware and software information for each route engine.
type RoutingEngine struct {
Model string
Version string
}
type commandXML struct {
Config string `xml:",innerxml"`
}
type commitError struct {
Path string `xml:"error-path"`
Element string `xml:"error-info>bad-element"`
Message string `xml:"error-message"`
}
type commitResults struct {
XMLName xml.Name `xml:"commit-results"`
Errors []commitError `xml:"rpc-error"`
}
type diffXML struct {
XMLName xml.Name `xml:"rollback-information"`
Error string `xml:"rpc-error>error-message"`
Config string `xml:"configuration-information>configuration-output"`
}
// cdiffXML - candidate config diff XML
type cdiffXML struct {
XMLName xml.Name `xml:"configuration-information"`
Error string `xml:"rpc-error>error-message"`
Config string `xml:"configuration-output"`
}
type hardwareRouteEngines struct {
XMLName xml.Name `xml:"multi-routing-engine-results"`
RE []hardwareRouteEngine `xml:"multi-routing-engine-item>chassis-inventory"`
}
type hardwareRouteEngine struct {
XMLName xml.Name `xml:"chassis-inventory"`
Serial string `xml:"chassis>serial-number"`
Description string `xml:"chassis>description"`
}
type versionRouteEngines struct {
XMLName xml.Name `xml:"multi-routing-engine-results"`
RE []versionRouteEngine `xml:"multi-routing-engine-item>software-information"`
}
type versionRouteEngine struct {
XMLName xml.Name `xml:"software-information"`
Hostname string `xml:"host-name"`
Platform string `xml:"product-model"`
PackageInfo []versionPackageInfo `xml:"package-information"`
}
type versionPackageInfo struct {
XMLName xml.Name `xml:"package-information"`
PackageName []string `xml:"name"`
SoftwareVersion []string `xml:"comment"`
}
// genSSHClientConfig is a wrapper function based around the auth method defined
// (user/password or private key) which returns the SSH client configuration used to
// connect.
func genSSHClientConfig(auth *AuthMethod) (*ssh.ClientConfig, error) {
var config *ssh.ClientConfig
if len(auth.Credentials) > 0 {
config = netconf.SSHConfigPassword(auth.Credentials[0], auth.Credentials[1])
return config, nil
}
if len(auth.PrivateKey) > 0 {
config, err := netconf.SSHConfigPubKeyFile(auth.Username, auth.PrivateKey, auth.Passphrase)
if err != nil {
return config, err
}
config.HostKeyCallback = ssh.InsecureIgnoreHostKey()
return config, nil
}
return config, errors.New("no credentials/keys available")
}
// NewSession establishes a new connection to a Junos device that we will use
// to run our commands against.
// Authentication methods are defined using the AuthMethod struct, and are as follows:
//
// username and password, SSH private key (with or without passphrase)
//
// Please view the package documentation for AuthMethod on how to use these methods.
//
// NOTE: most users should use this function, instead of the other NewSession* functions
func NewSession(host string, auth *AuthMethod) (*Junos, error) {
clientConfig, err := genSSHClientConfig(auth)
if err != nil {
return nil, err
}
return NewSessionWithConfig(host, clientConfig)
}
// NewSessionWithConfig establishes a new connection to a Junos device that we will use
// to run our commands against.
//
// This is especially useful if you need to customize the SSH connection beyond
// what's supported in NewSession().
func NewSessionWithConfig(host string, clientConfig *ssh.ClientConfig) (*Junos, error) {
s, err := netconf.DialSSH(host, clientConfig)
if err != nil {
return nil, errors.New(fmt.Sprintf("error connecting to %s - %s", host, err))
}
return NewSessionFromNetconf(s)
}
// NewSessionFromNetConn uses an existing net.Conn to establish a netconf.Session
//
// This is especially useful if you need to customize the SSH connection beyond
// what's supported in NewSession().
func NewSessionFromNetConn(host string, nc net.Conn, clientConfig *ssh.ClientConfig) (*Junos, error) {
s, err := netconf.NewSSHSession(nc, clientConfig)
if err != nil {
return nil, errors.New(fmt.Sprintf("error connecting to %s - %s", host, err))
}
return NewSessionFromNetconf(s)
}
// NewSessionFromNetconf uses an existing netconf.Session to run our commands against
//
// This is especially useful if you need to customize the SSH connection beyond
// what's supported in NewSession().
func NewSessionFromNetconf(s *netconf.Session) (*Junos, error) {
j := &Junos{
Session: s,
}
return j, j.GatherFacts()
}
// GatherFacts gathers basic information about the device.
//
// It's automatically called when using the provided NewSession* functions, but can be
// used if you create your own Junos sessions.
func (j *Junos) GatherFacts() error {
if j == nil {
return errors.New("attempt to call GatherFacts on nil Junos object")
}
s := j.Session
rex := regexp.MustCompile(`^.*\[(.*)\]`)
reply, err := s.Exec(netconf.RawMethod(rpcVersion))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
formatted := strings.Replace(reply.Data, "\n", "", -1)
if strings.Contains(reply.Data, "multi-routing-engine-results") {
var facts versionRouteEngines
err = xml.Unmarshal([]byte(formatted), &facts)
if err != nil {
return err
}
numRE := len(facts.RE)
hostname := facts.RE[0].Hostname
res := make([]RoutingEngine, 0, numRE)
for i := 0; i < numRE; i++ {
version := rex.FindStringSubmatch(facts.RE[i].PackageInfo[0].SoftwareVersion[0])
model := strings.ToUpper(facts.RE[i].Platform)
switch len(version) {
case 1:
res = append(res, RoutingEngine{Model: model, Version: version[0]})
case 2:
res = append(res, RoutingEngine{Model: model, Version: version[1]})
default:
}
}
j.Hostname = hostname
j.RoutingEngines = numRE
j.Platform = res
j.CommitTimeout = 0
return nil
}
var facts versionRouteEngine
err = xml.Unmarshal([]byte(formatted), &facts)
if err != nil {
return err
}
// res := make([]RoutingEngine, 0)
var res []RoutingEngine
hostname := facts.Hostname
version := rex.FindStringSubmatch(facts.PackageInfo[0].SoftwareVersion[0])
model := strings.ToUpper(facts.Platform)
res = append(res, RoutingEngine{Model: model, Version: version[1]})
j.Hostname = hostname
j.RoutingEngines = 1
j.Platform = res
j.CommitTimeout = 0
return nil
}
// Close disconnects our session to the device.
func (j *Junos) Close() {
j.Session.Transport.Close()
}
// Command executes any operational mode command, such as "show" or "request." If you wish to return the results
// of the command, specify the format, which must be "text" or "xml" as the second parameter (optional).
func (j *Junos) Command(cmd string, format ...string) (string, error) {
var command string
command = fmt.Sprintf(rpcCommand, cmd)
if len(format) > 0 && format[0] == "xml" {
command = fmt.Sprintf(rpcCommandXML, cmd)
}
if len(format) > 0 && format[0] == "json" {
command = fmt.Sprintf(rpcCommandJSON, cmd)
}
reply, err := j.Session.Exec(netconf.RawMethod(command))
if err != nil {
return "", err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return "", errors.New(m.Message)
}
}
if reply.Data == "" {
return "", errors.New("no output available - please check the syntax of your command")
}
if len(format) > 0 && format[0] == "text" {
var output commandXML
err = xml.Unmarshal([]byte(reply.Data), &output)
if err != nil {
return "", err
}
return output.Config, nil
}
return reply.Data, nil
}
// CommitHistory gathers all the information about the previous 5 commits.
func (j *Junos) CommitHistory() (*CommitHistory, error) {
var history CommitHistory
reply, err := j.Session.Exec(netconf.RawMethod(rpcCommitHistory))
if err != nil {
return nil, err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return nil, errors.New(m.Message)
}
}
if reply.Data == "" {
return nil, errors.New("could not load commit history")
}
formatted := strings.Replace(reply.Data, "\n", "", -1)
err = xml.Unmarshal([]byte(formatted), &history)
if err != nil {
return nil, err
}
return &history, nil
}
// Commit commits the configuration.
func (j *Junos) Commit() error {
var errs commitResults
reply, err := j.Session.Exec(netconf.RawMethod(rpcCommit))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
formatted := strings.Replace(reply.Data, "\n", "", -1)
err = xml.Unmarshal([]byte(formatted), &errs)
if err != nil {
return err
}
if errs.Errors != nil {
for _, m := range errs.Errors {
return errors.New(strings.Trim(m.Message, "[\r\n]"))
}
}
if j.CommitTimeout > 0 {
time.Sleep(j.CommitTimeout * time.Second)
}
return nil
}
// CommitAt commits the configuration at the specified time. Time must be in 24-hour HH:mm format.
// Specifying a commit message is optional.
func (j *Junos) CommitAt(time string, message ...string) error {
var errs commitResults
command := fmt.Sprintf(rpcCommitAt, time)
if len(message) > 0 {
command = fmt.Sprintf(rpcCommitAtLog, time, message[0])
}
reply, err := j.Session.Exec(netconf.RawMethod(command))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
formatted := strings.Replace(reply.Data, "\n", "", -1)
err = xml.Unmarshal([]byte(formatted), &errs)
if err != nil {
return err
}
if errs.Errors != nil {
for _, m := range errs.Errors {
return errors.New(strings.Trim(m.Message, "[\r\n]"))
}
}
return nil
}
// CommitCheck checks the configuration for syntax errors, but does not commit any changes.
func (j *Junos) CommitCheck() error {
var errs commitResults
reply, err := j.Session.Exec(netconf.RawMethod(rpcCommitCheck))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
formatted := strings.Replace(reply.Data, "\n", "", -1)
err = xml.Unmarshal([]byte(formatted), &errs)
if err != nil {
return err
}
if errs.Errors != nil {
for _, m := range errs.Errors {
return errors.New(strings.Trim(m.Message, "[\r\n]"))
}
}
return nil
}
// CommitConfirm rolls back the configuration after the delayed minutes.
func (j *Junos) CommitConfirm(delay int) error {
var errs commitResults
command := fmt.Sprintf(rpcCommitConfirm, delay)
reply, err := j.Session.Exec(netconf.RawMethod(command))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
formatted := strings.Replace(reply.Data, "\n", "", -1)
err = xml.Unmarshal([]byte(formatted), &errs)
if err != nil {
return err
}
if errs.Errors != nil {
for _, m := range errs.Errors {
message := fmt.Sprintf("[%s]\n %s\nError: %s", strings.Trim(m.Path, "[\r\n]"), strings.Trim(m.Element, "[\r\n]"), strings.Trim(m.Message, "[\r\n]"))
return errors.New(message)
}
}
return nil
}
// Diff compares candidate config to current (rollback 0) or previous rollback
// this is equivalent to 'show | compare' or 'show | compare rollback X' when
// in configuration mode
// RPC: <get-configuration compare="rollback" rollback="[0-49]" format="text"/>
// https://goo.gl/wFRMX9 (juniper.net)
func (j *Junos) Diff(rollback int) (string, error) {
var cd cdiffXML
command := fmt.Sprintf(rpcGetCandidateCompare, rollback)
reply, err := j.Session.Exec(netconf.RawMethod(command))
if err != nil {
return "", err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return "", errors.New(m.Message)
}
}
// formatted := strings.Replace(reply.Data, "\n", "", -1)
err = xml.Unmarshal([]byte(reply.Data), &cd)
if err != nil {
return "", err
}
if cd.Error != "" {
errMessage := strings.Trim(cd.Error, "\r\n")
return "", errors.New(errMessage)
}
return cd.Config, nil
}
// GetConfig returns the configuration starting at the given section. If you do not specify anything
// for section, then the entire configuration will be returned. Format must be "text" or "xml." You
// can do sub-sections by separating the section path with a ">" symbol, i.e. "system>login" or "protocols>ospf>area."
// The default option is to return the XML.
func (j *Junos) GetConfig(format string, section ...string) (string, error) {
command := fmt.Sprintf("<get-configuration format=\"%s\"><configuration>", format)
if len(section) > 0 {
secs := strings.Split(section[0], ">")
nSecs := len(secs) - 1
if nSecs >= 0 {
for i := 0; i < nSecs; i++ {
command += fmt.Sprintf("<%s>", secs[i])
}
command += fmt.Sprintf("<%s/>", secs[nSecs])
for j := nSecs - 1; j >= 0; j-- {
command += fmt.Sprintf("</%s>", secs[j])
}
command += fmt.Sprint("</configuration></get-configuration>")
}
}
if len(section) <= 0 {
command += "</configuration></get-configuration>"
}
reply, err := j.Session.Exec(netconf.RawMethod(command))
if err != nil {
return "", err
}
if len(reply.Data) < 50 {
return "", errors.New("the section you provided is not configured on the device")
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return "", errors.New(m.Message)
}
}
switch format {
case "text":
var output commandXML
// formatted := strings.Replace(reply.Data, "\n", "", -1)
err = xml.Unmarshal([]byte(reply.Data), &output)
if err != nil {
return "", err
}
if len(output.Config) <= 1 {
return "", errors.New("the section you provided is not configured on the device")
}
return output.Config, nil
case "xml":
return reply.Data, nil
}
return reply.Data, nil
}
// Config loads a given configuration file from your local machine,
// a remote (FTP or HTTP server) location, or via configuration statements
// from variables (type string or []string) within your script. Format must be
// "set", "text" or "xml".
func (j *Junos) Config(path interface{}, format string, commit bool) error {
var command string
switch format {
case "set":
switch path.(type) {
case string:
if strings.Contains(path.(string), "tp://") {
command = fmt.Sprintf(rpcConfigURLSet, path.(string))
}
if _, err := ioutil.ReadFile(path.(string)); err != nil {
command = fmt.Sprintf(rpcConfigStringSet, path.(string))
} else {
data, err := ioutil.ReadFile(path.(string))
if err != nil {
return err
}
command = fmt.Sprintf(rpcConfigFileSet, string(data))
}
case []string:
command = fmt.Sprintf(rpcConfigStringSet, strings.Join(path.([]string), "\n"))
}
case "text":
switch path.(type) {
case string:
if strings.Contains(path.(string), "tp://") {
command = fmt.Sprintf(rpcConfigURLText, path.(string))
}
if _, err := ioutil.ReadFile(path.(string)); err != nil {
command = fmt.Sprintf(rpcConfigStringText, path.(string))
} else {
data, err := ioutil.ReadFile(path.(string))
if err != nil {
return err
}
command = fmt.Sprintf(rpcConfigFileText, string(data))
}
case []string:
command = fmt.Sprintf(rpcConfigStringText, strings.Join(path.([]string), "\n"))
}
case "xml":
switch path.(type) {
case string:
if strings.Contains(path.(string), "tp://") {
command = fmt.Sprintf(rpcConfigURLXML, path.(string))
}
if _, err := ioutil.ReadFile(path.(string)); err != nil {
command = fmt.Sprintf(rpcConfigStringXML, path.(string))
} else {
data, err := ioutil.ReadFile(path.(string))
if err != nil {
return err
}
command = fmt.Sprintf(rpcConfigFileXML, string(data))
}
case []string:
command = fmt.Sprintf(rpcConfigStringXML, strings.Join(path.([]string), "\n"))
}
}
reply, err := j.Session.Exec(netconf.RawMethod(command))
if err != nil {
return err
}
if commit {
err = j.Commit()
if err != nil {
return err
}
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
return nil
}
// Lock locks the candidate configuration.
func (j *Junos) Lock() error {
reply, err := j.Session.Exec(netconf.RawMethod(rpcLock))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
if j.CommitTimeout > 0 {
time.Sleep(j.CommitTimeout * time.Second)
}
return nil
}
// Rescue will create or delete the rescue configuration given "save" or "delete" for the action.
func (j *Junos) Rescue(action string) error {
var command string
switch action {
case "save":
command = fmt.Sprintf(rpcRescueSave)
case "delete":
command = fmt.Sprintf(rpcRescueDelete)
default:
return errors.New("you must specify save or delete for a rescue config action")
}
reply, err := j.Session.Exec(netconf.RawMethod(command))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
return nil
}
// Rollback loads and commits the configuration of a given rollback number or rescue state, by specifying "rescue."
func (j *Junos) Rollback(option interface{}) error {
var command = fmt.Sprintf(rpcRollbackConfig, option)
if option == "rescue" {
command = fmt.Sprintf(rpcRescueConfig)
}
reply, err := j.Session.Exec(netconf.RawMethod(command))
if err != nil {
return err
}
err = j.Commit()
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
return nil
}
// Unlock unlocks the candidate configuration.
func (j *Junos) Unlock() error {
reply, err := j.Session.Exec(netconf.RawMethod(rpcUnlock))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
if j.CommitTimeout > 0 {
time.Sleep(j.CommitTimeout * time.Second)
}
return nil
}
// Reboot will reboot the device.
func (j *Junos) Reboot() error {
reply, err := j.Session.Exec(netconf.RawMethod(rpcReboot))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
return nil
}
// CommitFull does a full commit on the configuration, which requires all daemons to
// check and evaluate the new configuration. Useful for when you get an error with
// a commit or when you've changed the configuration significantly.
func (j *Junos) CommitFull() error {
reply, err := j.Session.Exec(netconf.RawMethod(rpcCommitFull))
if err != nil {
return err
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return errors.New(m.Message)
}
}
return nil
}
// SetCommitTimeout will add the given delay time (in seconds) to the following commit functions: Lock(),
// Commit() and Unlock(). When configuring multiple devices, or having a large configuration to push, this can
// greatly reduce errors (especially if you're dealing with latency).
func (j *Junos) SetCommitTimeout(delay int) {
d := time.Duration(delay)
j.CommitTimeout = d
}