1#!/router/bin/python-2.7.4
2
3from CPlatform import *
4import cmd
5import outer_packages
6import termstyle
7import os
8from misc_methods import load_object_config_file
9from optparse import OptionParser
10from CShowParser import PlatformResponseMissmatch, PlatformResponseAmbiguity
11
12class InteractivePlatform(cmd.Cmd):
13
14    intro = termstyle.green("\nInteractive shell to control a remote Cisco IOS platform.\nType help to view available pre-defined configurations\n(c) All rights reserved.\n")
15    prompt = '> '
16
17    def __init__(self, cfg_yaml_path = None, silent_mode = False, virtual_mode = False ):
18#       super(InteractivePlatform, self).__init__()
19        cmd.Cmd.__init__(self)
20        self.virtual_mode   = virtual_mode
21        self.platform       = CPlatform(silent_mode)
22        if cfg_yaml_path is None:
23            try:
24                cfg_yaml_path = raw_input(termstyle.cyan("Please enter a readable .yaml configuration file path: "))
25                cfg_yaml_path = os.path.abspath(cfg_yaml_path)
26            except KeyboardInterrupt:
27                exit(-1)
28        try:
29            self.device_cfg = CDeviceCfg(cfg_yaml_path)
30            self.platform.load_platform_data_from_file(self.device_cfg)
31            if not virtual_mode:
32                # if not virtual mode, try to establish a phyisical connection to platform
33                self.platform.launch_connection(self.device_cfg)
34
35        except Exception as inst:
36            print(termstyle.magenta(inst))
37            exit(-1)
38
39    def do_show_cfg (self, line):
40        """Outputs the loaded interface configuration"""
41        self.platform.get_if_manager().dump_if_config()
42        print(termstyle.green("*** End of interface configuration ***"))
43
44    def do_show_nat_cfg (self, line):
45        """Outputs the loaded nat provided configuration"""
46        try:
47            self.platform.dump_obj_config('nat')
48            print(termstyle.green("*** End of nat configuration ***"))
49        except UserWarning as inst:
50            print(termstyle.magenta(inst))
51
52
53    def do_show_static_route_cfg (self, line):
54        """Outputs the loaded static route configuration"""
55        try:
56            self.platform.dump_obj_config('static_route')
57            print(termstyle.green("*** End of static route configuration ***"))
58        except UserWarning as inst:
59            print(termstyle.magenta(inst))
60
61    def do_switch_cfg (self, cfg_file_path):
62        """Switch the current platform interface configuration with another one"""
63        if cfg_file_path:
64            cfg_yaml_path = os.path.abspath(cfg_file_path)
65            self.device_cfg = CDeviceCfg(cfg_yaml_path)
66            self.platform.load_platform_data_from_file(self.device_cfg)
67            if not self.virtual_mode:
68                self.platform.reload_connection(self.device_cfg)
69            print(termstyle.green("Configuration switching completed successfully."))
70        else:
71            print(termstyle.magenta("Configuration file is missing. Please try again."))
72
73    def do_load_clean (self, arg):
74        """Loads a clean configuration file onto the platform
75        Specify no arguments will load 'clean_config.cfg' file from bootflash disk
76        First argument is clean config filename
77        Second argument is platform file's disk"""
78        if arg:
79            in_val = arg.split(' ')
80            if len(in_val)==2:
81                self.platform.load_clean_config(in_val[0], in_val[1])
82            else:
83                print(termstyle.magenta("One of the config inputs is missing."))
84        else:
85            self.platform.load_clean_config()
86#           print termstyle.magenta("Configuration file definition is missing. use 'help load_clean' for further info.")
87
88    def do_basic_if_config(self, line):
89        """Apply basic interfaces configuartion to all platform interfaces"""
90        self.platform.configure_basic_interfaces()
91        print(termstyle.green("Basic interfaces configuration applied successfully."))
92
93    def do_basic_if_config_vlan(self, line):
94        """Apply basic interfaces configuartion with vlan to all platform interfaces"""
95        self.platform.configure_basic_interfaces(vlan = True)
96        print(termstyle.green("Basic VLAN interfaces configuration applied successfully."))
97
98    def do_pbr(self, line):
99        """Apply IPv4 PBR configuration on all interfaces"""
100        self.platform.config_pbr()
101        print(termstyle.green("IPv4 PBR configuration applied successfully."))
102
103    def do_pbr_vlan(self, line):
104        """Apply IPv4 PBR configuration on all VLAN interfaces"""
105        self.platform.config_pbr(vlan = True)
106        print(termstyle.green("IPv4 VLAN PBR configuration applied successfully."))
107
108    def do_no_pbr(self, line):
109        """Removes IPv4 PBR configuration from all interfaces"""
110        self.platform.config_no_pbr()
111        print(termstyle.green("IPv4 PBR configuration removed successfully."))
112
113    def do_no_pbr_vlan(self, line):
114        """Removes IPv4 PBR configuration from all VLAN interfaces"""
115        self.platform.config_no_pbr(vlan = True)
116        print(termstyle.green("IPv4 PBR VLAN configuration removed successfully."))
117
118    def do_nbar(self, line):
119        """Apply NBAR PD configuration on all interfaces"""
120        self.platform.config_nbar_pd()
121        print(termstyle.green("NBAR configuration applied successfully."))
122
123    def do_no_nbar(self, line):
124        """Removes NBAR PD configuration from all interfaces"""
125        self.platform.config_no_nbar_pd()
126        print(termstyle.green("NBAR configuration removed successfully."))
127
128    def do_static_route(self, arg):
129        """Apply IPv4 static routing configuration on all interfaces
130        Specify no arguments will apply static routing with following config:
131        1. clients_start            - 16.0.0.1
132        2. servers_start            - 48.0.0.1
133        3. dual_port_mask           - 1.0.0.0
134        4. client_destination_mask  - 255.0.0.0
135        5. server_destination_mask  - 255.0.0.0
136        """
137        if arg:
138            stat_route_dict = load_object_config_file(arg)
139#           else:
140#               print termstyle.magenta("Unknown configutaion option requested. use 'help static_route' for further info.")
141        else:
142            stat_route_dict = { 'clients_start' : '16.0.0.1',
143                                    'servers_start' : '48.0.0.1',
144                                    'dual_port_mask': '1.0.0.0',
145                                    'client_destination_mask' : '255.0.0.0',
146                                    'server_destination_mask' : '255.0.0.0' }
147        stat_route_obj = CStaticRouteConfig(stat_route_dict)
148        self.platform.config_static_routing(stat_route_obj)
149        print(termstyle.green("IPv4 static routing configuration applied successfully."))
150#           print termstyle.magenta("Specific configutaion is missing. use 'help static_route' for further info.")
151
152    def do_no_static_route(self, line):
153        """Removes IPv4 static route configuration from all non-duplicated interfaces"""
154        try:
155            self.platform.config_no_static_routing()
156            print(termstyle.green("IPv4 static routing configuration removed successfully."))
157        except UserWarning as inst:
158            print(termstyle.magenta(inst))
159
160    def do_nat(self, arg):
161        """Apply NAT configuration on all non-duplicated interfaces
162        Specify no arguments will apply NAT with following config:
163        1. clients_net_start        - 16.0.0.0
164        2. client_acl_wildcard_mask - 0.0.0.255
165        3. dual_port_mask           - 1.0.0.0
166        4. pool_start               - 200.0.0.0
167        5. pool_netmask             - 255.255.255.0
168        """
169        if arg:
170            nat_dict = load_object_config_file(arg)
171#           else:
172#               print termstyle.magenta("Unknown nat configutaion option requested. use 'help nat' for further info.")
173        else:
174#           print termstyle.magenta("Specific nat configutaion is missing. use 'help nat' for further info.")
175            nat_dict = { 'clients_net_start' : '16.0.0.0',
176                             'client_acl_wildcard_mask' : '0.0.0.255',
177                             'dual_port_mask' : '1.0.0.0',
178                             'pool_start' : '200.0.0.0',
179                             'pool_netmask' : '255.255.255.0' }
180        nat_obj = CNatConfig(nat_dict)
181        self.platform.config_nat(nat_obj)
182        print(termstyle.green("NAT configuration applied successfully."))
183
184    def do_no_nat(self, arg):
185        """Removes NAT configuration from all non-duplicated interfaces"""
186        try:
187            self.platform.config_no_nat()
188            print(termstyle.green("NAT configuration removed successfully."))
189        except UserWarning as inst:
190            print(termstyle.magenta(inst))
191
192
193    def do_ipv6_pbr(self, line):
194        """Apply IPv6 PBR configuration on all interfaces"""
195        self.platform.config_ipv6_pbr()
196        print(termstyle.green("IPv6 PBR configuration applied successfully."))
197
198    def do_ipv6_pbr_vlan(self, line):
199        """Apply IPv6 PBR configuration on all vlan interfaces"""
200        self.platform.config_ipv6_pbr(vlan = True)
201        print(termstyle.green("IPv6 VLAN PBR configuration applied successfully."))
202
203    def do_no_ipv6_pbr(self, line):
204        """Removes IPv6 PBR configuration from all interfaces"""
205        self.platform.config_no_ipv6_pbr()
206        print(termstyle.green("IPv6 PBR configuration removed successfully."))
207
208    def do_no_ipv6_pbr_vlan(self, line):
209        """Removes IPv6 PBR configuration from all VLAN interfaces"""
210        self.platform.config_no_ipv6_pbr(vlan = True)
211        print(termstyle.green("IPv6 VLAN PBR configuration removed successfully."))
212
213    def do_zbf(self, line):
214        """Apply Zone-Based policy Firewall configuration on all interfaces"""
215        self.platform.config_zbf()
216        print(termstyle.green("Zone-Based policy Firewall configuration applied successfully."))
217
218    def do_no_zbf(self, line):
219        """Removes Zone-Based policy Firewall configuration from all interfaces"""
220        self.platform.config_no_zbf()
221        print(termstyle.green("Zone-Based policy Firewall configuration removed successfully."))
222
223    def do_show_cpu_util(self, line):
224        """Fetches CPU utilization stats from the platform"""
225        try:
226            print(self.platform.get_cpu_util())
227            print(termstyle.green("*** End of show_cpu_util output ***"))
228        except PlatformResponseMissmatch as inst:
229            print(termstyle.magenta(inst))
230
231    def do_show_drop_stats(self, line):
232        """Fetches packet drop stats from the platform.\nDrop are summed and presented for both input and output traffic of each interface"""
233        print(self.platform.get_drop_stats())
234        print(termstyle.green("*** End of show_drop_stats output ***"))
235
236    def do_show_nbar_stats(self, line):
237        """Fetches NBAR classification stats from the platform.\nStats are available both as raw data and as percentage data."""
238        try:
239            print(self.platform.get_nbar_stats())
240            print(termstyle.green("*** End of show_nbar_stats output ***"))
241        except PlatformResponseMissmatch as inst:
242            print(termstyle.magenta(inst))
243
244    def do_show_nat_stats(self, line):
245        """Fetches NAT translations stats from the platform"""
246        print(self.platform.get_nat_stats())
247        print(termstyle.green("*** End of show_nat_stats output ***"))
248
249    def do_show_cft_stats(self, line):
250        """Fetches CFT stats from the platform"""
251        print(self.platform.get_cft_stats())
252        print(termstyle.green("*** End of show_sft_stats output ***"))
253
254    def do_show_cvla_memory_usage(self, line):
255        """Fetches CVLA memory usage stats from the platform"""
256        (res, res2) = self.platform.get_cvla_memory_usage()
257        print(res)
258        print(res2)
259        print(termstyle.green("*** End of show_cvla_memory_usage output ***"))
260
261    def do_clear_counters(self, line):
262        """Clears interfaces counters"""
263        self.platform.clear_counters()
264        print(termstyle.green("*** clear counters completed ***"))
265
266    def do_clear_nbar_stats(self, line):
267        """Clears interfaces counters"""
268        self.platform.clear_nbar_stats()
269        print(termstyle.green("*** clear nbar stats completed ***"))
270
271    def do_clear_cft_counters(self, line):
272        """Clears interfaces counters"""
273        self.platform.clear_cft_counters()
274        print(termstyle.green("*** clear cft counters completed ***"))
275
276    def do_clear_drop_stats(self, line):
277        """Clears interfaces counters"""
278        self.platform.clear_packet_drop_stats()
279        print(termstyle.green("*** clear packet drop stats completed ***"))
280
281    def do_clear_nat_translations(self, line):
282        """Clears nat translations"""
283        self.platform.clear_nat_translations()
284        print(termstyle.green("*** clear nat translations completed ***"))
285
286    def do_set_tftp_server (self, line):
287        """Configures TFTP access on platform"""
288        self.platform.config_tftp_server(self.device_cfg)
289        print(termstyle.green("*** TFTP config deployment completed ***"))
290
291    def do_show_running_image (self, line):
292        """Fetches currently loaded image of the platform"""
293        res = self.platform.get_running_image_details()
294        print(res)
295        print(termstyle.green("*** Show running image completed ***"))
296
297    def do_check_image_existence(self, arg):
298        """Check if specific image file (usually *.bin) is already stored in platform drive"""
299        if arg:
300            try:
301                res = self.platform.check_image_existence(arg.split(' ')[0])
302                print(res)
303                print(termstyle.green("*** Check image existence completed ***"))
304            except PlatformResponseAmbiguity as inst:
305                print(termstyle.magenta(inst))
306        else:
307            print(termstyle.magenta("Please provide an image name in order to check for existance."))
308
309    def do_load_image (self, arg):
310        """Loads a given image filename from tftp server (if not available on disk) and sets it as the boot image on the platform"""
311        if arg:
312            try:
313                self.platform.load_platform_image('asr1001-universalk9.BLD_V155_2_S_XE315_THROTTLE_LATEST_20150324_100047-std.bin')#arg.split(' ')[0])
314            except UserWarning as inst:
315                print(termstyle.magenta(inst))
316        else:
317            print(termstyle.magenta("Image filename is missing."))
318
319    def do_reload (self, line):
320        """Reloads the platform"""
321
322        ans = misc_methods.query_yes_no('This will reload the platform. Are you sure?', default = None)
323        if ans:
324            # user confirmed he wishes to reload the platform
325            self.platform.reload_platform(self.device_cfg)
326            print(termstyle.green("*** Platform reload completed ***"))
327        else:
328            print(termstyle.green("*** Platform reload aborted ***"))
329
330    def do_quit(self, arg):
331        """Quits the application"""
332        return True
333
334    def do_exit(self, arg):
335        """Quits the application"""
336        return True
337
338    def do_all(self, arg):
339        """Configures bundle of commands to set PBR routing"""
340        self.do_load_clean('')
341        self.do_set_tftp_server('')
342        self.do_basic_if_config('')
343        self.do_pbr('')
344        self.do_ipv6_pbr('')
345
346    def do_all_vlan(self, arg):
347        """Configures bundle of commands to set PBR routing using on vlan interfaces"""
348        self.do_load_clean('')
349        self.do_set_tftp_server('')
350        self.do_basic_if_config_vlan('')
351        self.do_pbr_vlan('')
352        self.do_ipv6_pbr_vlan('')
353
354
355
356if __name__ == "__main__":
357    parser = OptionParser(version="%prog 1.0 \t (C) Cisco Systems Inc.\n")
358    parser.add_option("-c", "--config-file", dest="cfg_yaml_path",
359                  action="store", help="Define the interface configuration to load the applicatino with.", metavar="FILE_PATH")
360    parser.add_option("-s", "--silent", dest="silent_mode", default = False,
361                  action="store_true", help="Silence the generated input when commands launched.")
362    parser.add_option("-v", "--virtual", dest="virtual_mode", default = False,
363                  action="store_true", help="Interact with a virtual router, no actual link will apply. Show commands are NOT available in this mode.")
364    (options, args) = parser.parse_args()
365
366    try:
367        InteractivePlatform(**vars(options)).cmdloop()
368
369    except KeyboardInterrupt:
370            exit(-1)
371
372