-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole.py
More file actions
executable file
·1532 lines (1341 loc) · 56.4 KB
/
console.py
File metadata and controls
executable file
·1532 lines (1341 loc) · 56.4 KB
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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: expandtab ts=4 sw=4 sts=4:
"""
console.py
Copyright (C) 2006-2011 Greg Anuzelli
contributions: Pavel Skovajsa
Derived from recipe on ASPN Cookbook
Recipe Author: James Thiele, http://www.eskimo.com/~jet/python/examples/cmd/
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import os
import time
import StringIO
import csv
import base64
import sys
from dynamips_lib import Router, Emulated_switch, DynamipsError, DynamipsWarning, IDLEPROPGET, IDLEPROPSHOW, IDLEPROPSET
from configobj import ConfigObj
from confConsole import AbstractConsole, confHypervisorConsole, confConsole
# True = Dynagen text-mode, False = GNS3 GUI-mode.
if __name__ == 'console':
PureDynagen = True
else:
PureDynagen = False
# determine if we are in the debugger
try:
DBGPHideChildren
except NameError:
DEBUGGER = False
else:
DEBUGGER = True
# Import readline if it is available. If it is, tab completion will work
try:
import readline
except ImportError:
pass
# Progress bar class from http://code.activestate.com/recipes/168639/
class progressBar:
def __init__(self, minValue = 0, maxValue = 10, totalWidth=12):
self.progBar = "[]" # This holds the progress bar string
self.min = minValue
self.max = maxValue
self.span = maxValue - minValue
self.width = totalWidth
self.amount = 0 # When amount == max, we are 100% done
self.updateAmount(0) # Build progress bar string
def updateAmount(self, newAmount = 0):
if newAmount < self.min: newAmount = self.min
if newAmount > self.max: newAmount = self.max
self.amount = newAmount
# Figure out the new percent done, round to an integer
diffFromMin = float(self.amount - self.min)
percentDone = (diffFromMin / float(self.span)) * 100.0
percentDone = round(percentDone)
percentDone = int(percentDone)
# Figure out how many hash bars the percentage should be
allFull = self.width - 2
numHashes = (percentDone / 100.0) * allFull
numHashes = int(round(numHashes))
# build a progress bar with hashes and spaces
self.progBar = "[" + '#'*numHashes + ' '*(allFull-numHashes) + "]"
# figure out where to put the percentage, roughly centered
percentPlace = (len(self.progBar) / 2) - len(str(percentDone))
percentString = str(percentDone) + "%"
# slice the percentage into the bar
self.progBar = self.progBar[0:percentPlace] + percentString + self.progBar[percentPlace+len(percentString):]
def __str__(self):
return str(self.progBar)
class Console(AbstractConsole):
"""Interactive console for users to manage dynamips"""
def __init__(self, dynagen):
AbstractConsole.__init__(self)
self.prompt = '=> '
self.intro = 'Dynagen management console for Dynamips and Qemuwrapper/VBoxwrapper ' + self.namespace.VERSION + '\nCopyright (c) 2005-2011 Greg Anuzelli, contributions Pavel Skovajsa, Jeremy Grossmann & Alexey Eromenko "Technologov"\n'
self.dynagen = dynagen
## Command definitions ##
def delayWithProgress(self, seconds):
""" Sleep while displaying a progresss bar
"""
width = 40 # Width of progress bar in characters
interval = float(seconds)/width
prog = progressBar(0, seconds, width)
i=0
while i < seconds:
i += interval
prog.updateAmount(i)
print width*"\b",
print prog, "\r",
time.sleep(interval)
print
def do_list(self, args):
"""list
\tList all devices"""
table = []
print '%-10s %-10s %-10s %-27s %-10s %-10s' % (
'Name',
'Type',
'State',
'Server',
'Console',
'AUX'
)
for device in self.dynagen.devices.values():
row = []
row.append('%-10s' % device.name)
try:
model = device.model_string
row.append('%-10s' % model)
except AttributeError:
row.append('%-10s' % device.adapter)
try:
row.append('%-10s' % device.state)
except AttributeError:
row.append('%-10s' % 'always on')
try:
server = device.dynamips.host + ":" + str(device.dynamips.port)
row.append('%-20s' % server)
except AttributeError:
row.append('%-20s' % 'n/a')
try:
row.append('%-10s' % device.console)
except AttributeError:
row.append('%-10s' % 'n/a')
try:
row.append('%-10s' % device.aux)
except AttributeError:
row.append('%-10s' % 'n/a')
table.append(row)
table.sort(con_cmp) # Sort the table by the console port #
for line in table:
for item in line:
print item,
print
if PureDynagen:
def do_conf(self, args):
"""conf <hypervisor address>:<hypervisor port>
\tswitch into configuration mode of the specific hypervisor eg. 'conf localhost'. If the hypervisor does not exist it will be created.
conf
\tswitch into global config mode"""
if '?' in args:
print self.do_conf.__doc__
return
#if this is a conf <nothing> command go into global config mode
if args.strip() == "":
nested_cmd = confConsole(self.dynagen, self)
nested_cmd.cmdloop()
return
#if this is a conf <hypervisor_name> go into hypervisor config mode
#check if this hypervisor already exists
found = False
params = args.split(":")
if len(params) == 1:
hyp_name = params[0]
hyp_port = 7200
elif len(params) == 2:
try:
hyp_name = params[0]
hyp_port = int(params[1])
except (AttributeError, ValueError):
error('Syntax error in ' + args + ' . Use <hypervisor address>:<hypervisor port> syntax')
return
else:
error('Syntax error in ' + params + ' . Use <hypervisor address>:<hypervisor port> syntax')
return
for server in self.dynagen.dynamips.values():
if hyp_name == server.host and hyp_port == server.port:
found = True
break
if not found:
#if not found create the hypervisor instance...
dynamips = self.dynagen.create_dynamips_hypervisor(hyp_name, hyp_port)
#call hypervisor config mode
if dynamips != None:
nested_cmd = confHypervisorConsole(dynamips, self.dynagen)
nested_cmd.cmdloop()
else:
#looks like we found an already existing hypervisor instance, so let's jump into nested conf Cmd to configure it
nested_cmd = confHypervisorConsole(server, self.dynagen)
nested_cmd.cmdloop()
def do_suspend(self, args):
"""suspend {/all | router1 [router2] ...}
\tsuspend all or a specific router(s)"""
if '?' in args or args.strip() == "":
print self.do_suspend.__doc__
return
devices = args.split(" ")
if '/all' in devices:
for device in self.dynagen.devices.values():
try:
for line in device.suspend():
print line.strip()
except IndexError:
pass
except AttributeError:
# If this device doesn't support suspend just ignore it
pass
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
return
for device in devices:
try:
print self.dynagen.devices[device].suspend()[0].strip()
except IndexError:
pass
except (KeyError, AttributeError):
error('invalid device: ' + device)
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
def do_vboxexec(self, args):
"""vboxexec <VBOX device> <command>\nVirtualBox GuestControl execute sends a command to VirtualBox guest and prints it's output (experimental feature).
This requires VirtualBox Guest Additions to be installed inside the guest VM."""
if '?' in args or args.strip() == "":
print self.do_vboxexec.__doc__
return
devices = args.split(" ")
#if devname in devices[0]:
devname = devices[0]
#print "ADEBUG: console.py: devname = ", devname
try:
device = self.dynagen.devices[devname]
if not isinstance(device, self.namespace.AnyVBoxEmuDevice):
error("Device is not VirtualBox device: " + devname)
return
result = device.vboxexec(args.split(" ")[1:])
#print "ADEBUG: console.py: vboxexec raw result = ", result
#If we got incorrect result, just drop it.
try:
if not result[0][0:10] == "100-result":
#print "ADEBUG: console.py: result[0][0:9] = %s" % result[0][0:9]
return
except:
return
# vboxwrapper TCP server incorrectly formats text by adding double
#line-ending in UNIX style, which we convert to single line-end in client-native style
print result[0][10:].replace('\n\n', os.linesep)
except IndexError:
pass
except (KeyError, AttributeError):
error('invalid device: ' + devname)
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
def do_start(self, args):
"""start {/all [delay] | router1 [router2] ...}
\tstart all or a specific router(s)
\tFor start /all only, a delay can be specified. Dynagen will pause this many seconds between starting devices.
"""
startdelay = self.dynagen.startdelay
if '?' in args or args.strip() == "":
print self.do_start.__doc__
return
devices = args.split(" ")
if '/all' in devices:
try:
delay = devices[1]
except IndexError:
# No delay specified, use default
delay = startdelay
try:
delay = int(delay)
except ValueError:
print self.do_start.__doc__
return
for device in self.dynagen.devices.values():
try:
if device.idlepc == None:
if self.dynagen.useridledb and device.imagename in self.dynagen.useridledb:
device.idlepc = self.dynagen.useridledb[device.imagename]
else:
print 'Warning: Starting %s with no idle-pc value' % device.name
self.dynagen.check_ghost_file(device)
self.dynagen.jitsharing()
for line in device.start():
print line.strip()
if delay != 0 and device != self.dynagen.devices.values()[-1]:
# don't delay if there is none or if this is the last device
print 'Delaying start of next device for %i seconds...' % delay
self.delayWithProgress(delay)
except IndexError:
pass
except AttributeError:
# If this device doesn't support start just ignore it
pass
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
return
for devname in devices:
try:
device = self.dynagen.devices[devname]
if device.idlepc == None:
if self.dynagen.useridledb and device.imagename in self.dynagen.useridledb:
device.idlepc = self.dynagen.useridledb[device.imagename]
else:
print 'Warning: Starting %s with no idle-pc value' % device.name
if not self.dynagen.check_ghost_file(device):
return
self.dynagen.jitsharing()
for line in device.start():
print line.strip()
except IndexError:
pass
except (KeyError, AttributeError):
error('invalid device: ' + devname)
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
def do_stop(self, args):
"""stop {/all | router1 [router2] ...}
\tstop all or a specific router(s)"""
if '?' in args or args.strip() == "":
print self.do_stop.__doc__
return
devices = args.split(" ")
if '/all' in devices:
for device in self.dynagen.devices.values():
try:
for line in device.stop():
print line.strip()
except IndexError:
pass
except AttributeError:
# If this device doesn't support stop just ignore it
pass
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
return
for device in devices:
try:
print self.dynagen.devices[device].stop()[0].strip()
except IndexError:
pass
except (KeyError, AttributeError):
error('invalid device: ' + device)
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
def do_resume(self, args):
"""resume {/all | router1 [router2] ...}
\tresume all or a specific router(s)"""
if '?' in args or args.strip() == "":
print self.do_resume.__doc__
return
devices = args.split(" ")
if '/all' in devices:
for device in self.dynagen.devices.values():
try:
for line in device.resume():
print line.strip()
except IndexError:
pass
except AttributeError:
# If this device doesn't support resume just ignore it
pass
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
return
for device in devices:
try:
print self.dynagen.devices[device].resume()[0].strip()
except IndexError:
pass
except (KeyError, AttributeError):
error('invalid device: ' + device)
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
def do_reload(self, args):
"""reload {/all | router1 [router2] ...}
\treload all or a specific router(s)"""
if '?' in args or args.strip() == "":
print self.do_reload.__doc__
return
devices = args.split(" ")
if '/all' in devices:
for device in self.dynagen.devices.values():
try:
for line in device.stop():
print line.strip()
time.sleep(1)
for line in device.start():
print line.strip()
except IndexError:
pass
except AttributeError:
# If this device doesn't support stop/start just ignore it
pass
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
return
for device in devices:
try:
print self.dynagen.devices[device].stop()[0].strip()
time.sleep(1)
print self.dynagen.devices[device].start()[0].strip()
except IndexError:
pass
except (KeyError, AttributeError):
error('invalid device: ' + device)
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
def do_ver(self, args):
"""Print the dynagen version and credits"""
print 'Dynagen version ' + self.namespace.VERSION
print 'hypervisor version(s):'
for d in self.dynagen.dynamips.values():
print ' %s at %s:%i has version %s' % (d.type, d.host, d.port, d.version)
print """
Credits:
Dynagen is written by Greg Anuzelli
Contributing developers: Pavel Skovajsa, Jeremy Grossmann & Alexey Eromenko "Technologov"
Qemuwrapper: Thomas Pani & Jeremy Grossmann
VBoxwrapper: Thomas Pani, Jeremy Grossmann & Alexey Eromenko "Technologov"
Pemu: Milen Svobodnikov
Thanks to the authors of the ConfObj library
And big thanks of course to Christophe Fillot as the author of Dynamips.
"""
if PureDynagen:
def do_shell(self, args):
"""Pass command to a system shell when line begins with '!'"""
os.system(args)
def do_telnet(self, args):
"""telnet {/all | router1 [router2] ...}
\ttelnet to the console(s) of all or a specific router(s)
\tThis is identical to the console command."""
if '?' in args or args.strip() == "":
print self.do_telnet.__doc__
return
Console.do_console(self, args)
def do_console(self, args):
"""console {/all | router1 [router2] ...}
\tconnect to the console(s) of all or a specific router(s)
"""
if '?' in args or args.strip() == "":
print self.do_telnet.__doc__
return
devices = args.split(" ")
if '/all' in args.split(" "):
# Set devices to all the devices
devices = self.dynagen.devices.values()
else:
devices = []
for device in args.split(" "):
# Create a list of all the device objects
try:
devices.append(self.dynagen.devices[device])
except KeyError:
error('unknown device: ' + device)
for device in devices:
try:
if not device.isrouter:
continue
if device.state != 'running':
print 'Skipping %s device: %s' % (device.state, device.name)
continue
self.telnet(device.name)
except IndexError:
pass
except (KeyError, AttributeError):
error('invalid device: ' + device.name)
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
def do_aux(self, args):
"""aux {/all | router1 [router2] ...}
\tconnect to the AUX port(s) of all or a specific router(s)
"""
if '?' in args or args.strip() == "":
print self.do_aux.__doc__
return
devices = args.split(" ")
if '/all' in args.split(" "):
# Set devices to all the devices
devices = self.dynagen.devices.values()
else:
devices = []
for device in args.split(" "):
# Create a list of all the device objects
try:
devices.append(self.dynagen.devices[device])
except KeyError:
error('unknown device: ' + device)
for device in devices:
try:
if not device.isrouter:
continue
if device.state != 'running':
print 'Skipping %s device: %s' % (device.state, device.name)
continue
self.aux(device.name)
except IndexError:
pass
except (KeyError, AttributeError):
error('invalid device: ' + device.name)
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
def show_device(self, params):
"""show device {something} command prints the output by calling get_device_info function"""
if len(params) == 1: #if this is only 'show device' command print info about all devices
output = []
for device in self.dynagen.devices.values():
#if it is a router or other emulated device
if isinstance(device, (self.namespace.Router, self.namespace.AnyEmuDevice, self.namespace.AnyVBoxEmuDevice, self.namespace.FRSW, self.namespace.ATMBR, self.namespace.ATMSW, self.namespace.ETHSW)):
output.append(device.info())
output.sort()
for devinfo in output:
print devinfo
elif len(params) == 2:
#if this is 'show device {something}' command print info about specific device
try:
device = self.dynagen.devices[params[1]]
if isinstance(device, (self.namespace.Router, self.namespace.AnyEmuDevice, self.namespace.AnyVBoxEmuDevice, self.namespace.FRSW, self.namespace.ATMBR, self.namespace.ATMSW, self.namespace.ETHSW)):
print device.info()
except KeyError:
error('unknown device: ' + params[1])
else:
error('invalid show device command')
def show_start(self):
"""show start command reads the config file on disk and prints it out"""
startup_config_tuple = self.dynagen.get_starting_config()
#print out the start_config
for line in startup_config_tuple:
print line
def show_run(self, params):
"""update the running config and print it out"""
running_config_tuple = self.dynagen.get_running_config(params)
for line in running_config_tuple:
#we do not want to see that BIG configuration blob on the screen
if line.find('configuration') == -1:
print line
def show_mac(self, params):
"""print out the mac table of the ETHSW in params"""
try:
result = self.dynagen.devices[params[1]].show_mac()
for chunks in result:
lines = chunks.strip().split('\r\n')
for line in lines:
if line != '100-OK':
print line[4:]
except IndexError:
error('missing device')
except (KeyError, AttributeError):
error('invalid device: ' + params[1])
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
def do_show(self, args):
"""show mac <ethernet_switch_name>
\tshow the mac address table of an ethernet switch
show device
\tshow detail information about every device in current lab
show device <device_name>
\tshow detail information about a device
show start
\tshow startup lab configuration
show run
\tshow running configuration of current lab
show run <device_name>
\tshow running configuration of a router
"""
if '?' in args or args.strip() == "":
print self.do_show.__doc__
return
params = args.split(" ")
#if this is 'show router {something}' command print the output by calling router_Info function
if params[0] == 'device':
self.show_device(params)
elif params[0] == 'start':
#if this is 'show start' command read the config file on disk and print it out
self.show_start()
elif params[0] == 'run':
#if this is a 'show run' command update the running config and print it out
self.show_run(params)
elif params[0] == 'mac':
#if this is a 'show mac <ethernet_switch_name>' command print out the mac table of the switch
self.show_mac(params)
else:
error('invalid show command')
def do_copy(self, args):
"""copy run start
\tcopy running topology into startup topology"""
if '?' in args or args.strip() == "":
print self.do_copy.__doc__
return
self.dynagen.update_running_config(need_active_config=True)
params = args.split(" ")
if len(params) == 2 and params[0] == 'run' and params[1] == 'start':
filename = self.dynagen.global_filename
self.dynagen.running_config.filename = filename
self.dynagen.running_config.write()
self.dynagen.running_config.filename = None
else:
error('invalid copy command')
def do_clear(self, args):
"""clear mac <ethernet_switch_name>
\tclear the mac address table of an ethernet switch"""
if '?' in args or args.strip() == "":
print self.do_clear.__doc__
return
params = args.split(" ")
if params[0].lower() == 'mac':
try:
print self.dynagen.devices[params[1]].clear_mac()[0].strip()
except IndexError:
error('missing device')
except (KeyError, AttributeError):
error('invalid device: ' + params[1])
except DynamipsError, e:
error(e)
except DynamipsWarning, e:
print "Note: " + str(e)
else:
error('invalid clear command')
def do_save(self, args):
"""save {/all | router1 [router2] ...}
\tstores router configs in the network file"""
if '?' in args or args.strip() == "":
print self.do_save.__doc__
return
netfile = self.dynagen.globalconfig
if '/all' in args.split(" "):
# Set devices to all the devices
devices = self.dynagen.devices.values()
else:
devices = []
for device in args.split(" "):
# Create a list of all the device objects
try:
devices.append(self.dynagen.devices[device])
except KeyError:
error('unknown device: ' + device)
# Get the config for each router and store it in the config dict
for device in devices:
try:
config = device.config_b64
except AttributeError:
# This device doesn't support export
continue
except DynamipsError, e:
print e
# Try saving the other devices though
continue
except DynamipsWarning, e:
print "Note: " + str(e)
# What server and port is this device on?
host = device.dynamips.host
port = device.dynamips.port
# Find the config section for this device
if netfile.has_key(host + ":" + str(port)):
serverSection = host + ":" + str(port)
elif netfile.has_key(host):
serverSection = host
else:
error('cannot find server section for device: ' + device.name)
for section in netfile[serverSection].sections:
# Check to see if 1) this device is a router, and
# 2) if it is the section for the device we need to save
try:
(devtype, devname) = section.split()
except ValueError:
continue
if devtype.lower() == 'router' and devname == device.name:
netfile[serverSection][section]['configuration'] = config
# And populate the configurations dictionary
self.dynagen.configurations[device.name] = config
print 'saved configuration from: ' + device.name
netfile.write()
def do_push(self, args):
"""push {/all | router1 [router2] ...}
\tpushes router configs from the network file to the router's nvram
"""
if '?' in args or args.strip() == "":
print self.do_push.__doc__
return
configurations = self.dynagen.configurations
if '/all' in args.split(" "):
# Set devices to all the devices
devices = self.dynagen.devices.values()
else:
devices = []
for device in args.split(" "):
# Create a list of all the device objects
try:
devices.append(self.dynagen.devices[device])
except KeyError:
error('unknown device: ' + device)
# Set the config for each router
for device in devices:
try:
device.config_b64 = configurations[device.name]
except AttributeError:
# This device doesn't support importing
continue
except KeyError:
print 'No saved configuration found for device: ' + device.name
continue
except DynamipsError, e:
print e
# Try saving the other devices though
continue
except DynamipsWarning, e:
print "Note: " + str(e)
print 'Pushed config to: ' + device.name
def do_export(self, args):
'''export {/all | router1 [router2] ...} "directory"
\tsaves router configs individual files in "directory"
\tEnclose the directory in quotes if there are spaces in the filespec.
'''
if '?' in args or args.strip() == "":
print self.do_export.__doc__
return
try:
items = getItems(args)
except DynamipsError, e:
error(e)
return
except DynamipsWarning, e:
print "Note: " + str(e)
if len(items) < 2:
print self.do_export.__doc__
return
# The last item is the directory (or should be anyway)
directory = items.pop()
if '/all' in items:
# Set devices to all the devices
devices = self.dynagen.devices.values()
else:
devices = []
for device in items:
# Create a list of all the device objects
try:
devices.append(self.dynagen.devices[device])
except KeyError:
error('unknown device: ' + device)
return
# Set the current directory to the one that contains our network file
try:
netdir = os.getcwdu()
subdir = os.path.dirname(self.dynagen.global_filename)
self.debug('current dir is -> ' + os.getcwdu())
if subdir != "":
self.debug("changing dir to -> " + subdir)
os.chdir(subdir)
except OSError, e:
error(e)
os.chdir(netdir) # Reset the current working directory
return
try:
self.debug('making -> ' + str(directory))
os.makedirs(directory)
except OSError:
# Directory exists
result = raw_input('The directory %s already exists. Ok to overwrite (Y/N)? ' % directory)
if result.lower() != 'y':
os.chdir(netdir) # Reset the current working directory
return
# Get the config for each router and store it in the config dict
for device in devices:
try:
config = base64.decodestring(device.config_b64)
config = config.replace('\r', "")
except AttributeError:
# This device doesn't support export
continue
except DynamipsError, e:
print e
# Try saving the other devices though
continue
except DynamipsWarning, e:
print "Note: " + str(e)
except TypeError:
error('Unknown error exporting config for ' + device.name)
continue
# Write out the config to a file
print 'Exporting %s to %s' % (device.name, directory + os.sep + device.name + '.cfg')
try:
f = open(directory + os.sep + device.name + '.cfg', 'w')
f.write(config)
f.close()
except IOError, e:
error(e)
os.chdir(netdir) # Reset the current working directory
return
# Change directory back to net dir for subsequent execution
os.chdir(netdir)
def do_import(self, args):
'''import {/all | router1 [router2] "directory"
\timport all or individual configuration files
\tEnclose the directory or filename in quotes if there are spaces in the filespec.'''
if '?' in args or args.strip() == "":
print self.do_import.__doc__
return
items = getItems(args)
# The last item is the directory (or should be anyway)
directory = items.pop()
# Set the current directory to the one that contains our network file
try:
netdir = os.getcwdu()
subdir = os.path.dirname(self.dynagen.global_filename)
self.debug('current dir is -> ' + os.getcwdu())
if subdir != "":
self.debug("changing dir to -> " + subdir)
os.chdir(subdir)
except OSError, e:
error(e)
return
# Walk through all the config files, and attempt to import them
try:
contents = os.listdir(directory)
except OSError, e:
error(e)
return
for file in contents:
if file[-4:].lower() == '.cfg':
device = file[:-4]
if '/all' in items or device in items:
print 'Importing %s from %s' % (device, file)
try:
f = open(directory + os.sep + file, 'r')
config = f.read()
config = '!\n' + config
f.close()
# Encodestring puts in a bunch of newlines. Split them out then join them back together
encoded = ("").join(base64.encodestring(config).split())
self.dynagen.devices[device].config_b64 = encoded
except IOError, e:
error(e)
os.chdir(netdir) # Reset the current working directory
return
except KeyError:
error('Ignoring unknown device: ' + device)
except DynamipsError, e:
# Don't return, continue trying to import the other devices
error(e)
except DynamipsWarning, e:
# Don't return, continue trying to import the other devices
print "Note: " + str(e)
os.chdir(netdir)
def do_filter(self, args):
"""filter device interface filter_name direction [options]
\tapplies a connection filter
\tExamples:
\tfilter R1 s1/0 freq_drop in 50 -- Drops 1 out of every 50 packets inbound to R1 s1/0
\tfilter R1 s1/0 none in -- Removes all inbound filters from R1 s1/0
\tfilter R1 s1/0 monitor both eth2 -- Span all traffic on s1/0 to eth2"""
filters = ['freq_drop', 'capture', 'monitor', 'none'] # The known list of filters