diff --git a/demo_docs/Cisco Partner Nexus 9000 Demo Guide.docx b/demo_docs/Cisco Partner Nexus 9000 Demo Guide.docx
new file mode 100644
index 00000000..60e3eb89
Binary files /dev/null and b/demo_docs/Cisco Partner Nexus 9000 Demo Guide.docx differ
diff --git a/demo_docs/N9K_Demo_Overview.pptx b/demo_docs/N9K_Demo_Overview.pptx
new file mode 100644
index 00000000..f064b31d
Binary files /dev/null and b/demo_docs/N9K_Demo_Overview.pptx differ
diff --git a/demo_scripts/README.md b/demo_scripts/README.md
new file mode 100644
index 00000000..de0cb278
--- /dev/null
+++ b/demo_scripts/README.md
@@ -0,0 +1,20 @@
+Nexus 9000 Partner Demo Scripts
+===============================
+Welcome to the OneCloud Consulting Nexus 9000 demo script repository.
+
+These scripts were developed and tested on a Nexus 9000 C9372PX chassis running 7.0(3)I1(2).
+
+Summary
+========
+1. __find_freeip.py__ : Pings a range of IP addresses then prints which are UP followed by a summary of addresses that are unused.
+2. __sh_switch_details.py__ : Displays specific details from neighbor based on its IP address. Demonstrates use of a single programmatic Python instruction versus a series of CLI commands to obtain the same information.
+3. __cdp.py__ : Configures interface descriptions based on CDP information.
+4. __lldp.py__ : Configured interface descriptions based on LLDP information.
+5. __ospf.py__ : Provides menu driven options to configure OSPF interface attributes (area/cost).
+6. __pim.py__ : Provides menu driven options to configure PIM interface attributes.
+7. __cleanup.py__ : Provides menu driven options to cleanup demo configurations.
+8. __sh_version.py__ : Uses NX-API to compare expected NX-OS version against actual NX-OS versions running in the network.
+9. __sh_proc_cpu_sort.py__ : Checks CPU health of switch at regular intervals with option to log output to file for TAC.
+10. __sh_proc_mem.py__ : Checks memory utilization of switch at regular intervals with option to log to file for TAC.
+11. __sh_int_count.py__ : Checks interface packet count at regular intervals with option to log to file for TAC.
+
diff --git a/demo_scripts/cdp.py b/demo_scripts/cdp.py
new file mode 100644
index 00000000..95763056
--- /dev/null
+++ b/demo_scripts/cdp.py
@@ -0,0 +1,120 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:On-Box
+:Title:Interface Description configuration
+:Short Description:To dynamically configure interface descriptions
+:Long Description:Check the CDP state and modify the interface description accordingly.
+:Input:command to check the CDP state and based on the command output,
+ modify the description of the interface
+:Output:interface description should be updated
+"""
+
+import os
+from cli import *
+import sys
+
+"""
+
+Class to update the interface description based on the
+CDP state
+"""
+
+class Interface_Desc:
+
+ interface_message = {}
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+ versioncmd = "show version"
+ out = json.loads(clid(versioncmd))
+ chassis_id = out['chassis_id']
+ osversion = out['rr_sys_ver']
+ cpu_name = out['cpu_name']
+ memory = out['memory']
+ processor_board = out['proc_board_id']
+ device = out['host_name']
+ bootflash = out['bootflash_size']
+
+ print "Nexus Switch OS version is :" , osversion
+ print "Chassis ID is :", chassis_id
+ print cpu_name + "with" + str(memory) + "KB of memory"
+ print "Processor Board ID is " + processor_board
+
+ print "Host Name : " + device
+ print "Bootflash : " + str(bootflash) + ' ' + "KB"
+ print "\n"
+
+ def cdp_status(self):
+ intob = Interface_Desc()
+
+ #check CDP is enabled or not
+ cdp_stat = "show cdp global"
+ stat = json.loads(clid(cdp_stat))
+
+ if (stat['cdp_global_enabled'] == 'enabled'):
+ print "CDP is enabled on the Host Switch"
+ cdp_nei = "show cdp nei"
+ status = json.loads(clid(cdp_nei))
+ status_list = status['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info']
+ cdp_dict = {}
+
+ if (isinstance(status_list, list)):
+ for i in status_list:
+ for key,value in i.items():
+ if (key == 'device_id'):
+ cdp_dict.update({key:value})
+ if (key == 'intf_id'):
+ cdp_dict.update({key:value})
+ if (key == 'port_id'):
+ cdp_dict.update({key:value})
+ if (key == 'capability'):
+ cdp_dict.update({key:value})
+ intob.updateinterface(cdp_dict)
+ elif (isinstance(status_list, dict)):
+ for key,value in status_list.items():
+ if (key == 'device_id'):
+ cdp_dict.update({key:value})
+ if (key == 'intf_id'):
+ cdp_dict.update({key:value})
+ if (key == 'port_id'):
+ cdp_dict.update({key:value})
+ if (key == 'capability'):
+ cdp_dict.update({key:value})
+ intob.updateinterface(cdp_dict)
+ else:
+ print "Not implemented for this response type"
+
+ else:
+ print "CDP is not enabled on the Host Switch.Please check the CDP manual to enable it. "
+ exit(1)
+
+ #update the interface description
+ def updateinterface(self, data):
+ for key,value in data.iteritems():
+ if (key == 'intf_id'):
+ cmd1 = "interface" + ' ' + value
+ desc = "description" + ' ' + "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+ msg = "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+
+ cmd = "conf t" + ' ' + " ;" + ' ' + cmd1 + ' ' + ";" + ' ' + desc
+ cli(cmd)
+ print "\n"
+ print "Interface" + ' ' + data['intf_id'] + ' ' + "description is updated as : " + ' ' + msg
+ if (data['capability']):
+ print "Neighbor device" + ' ' + data['device_id'] + ' ' + "is capable as : "
+ for i in data['capability']:
+ print str(i)
+
+ #print data['capability']
+
+
+
+if __name__ == '__main__':
+ interfaceob = Interface_Desc()
+ interfaceob.nexus_version()
+ interfaceob.cdp_status()
+
+
+
+
diff --git a/demo_scripts/cleanup.py b/demo_scripts/cleanup.py
new file mode 100644
index 00000000..5027a3e4
--- /dev/null
+++ b/demo_scripts/cleanup.py
@@ -0,0 +1,225 @@
+"""
+ Cisco Nexus 9000 Switch On-Box script for cleaning
+ repetitive switch configurations such as disabling
+ features, removing IP addresses from all interfaces,
+ and so on.
+"""
+from cli import *
+import time
+
+class Cleanup(object):
+
+ def __init__(self):
+ """ No variables are required for this class. """
+
+ def print_Banner(self):
+ msg = '\n _ _ _ _ _ _ _'
+ msg += '\n / \\ / \\ / \\ / \\ / \\ / \\ / \\'
+ msg += '\n ( C | l | e | a | n | u | p )'
+ msg += '\n \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/'
+ msg += '\n\nCisco Nexus 9000 Switch On-Box script'
+ msg += '\nfor cleaning repetitive switch configurations.\n'
+ msg += '\nDeveloped By: OneCloud Consulting\n'
+ msg += 'Please contact info@1-cloud.net for any queries.\n'
+ print msg
+
+ def print_Menu(self):
+ print "-"*25 + " Menu Options " + "-"*25
+ print "1) Remove all 'feature' CLI statements."
+ print "2) Remove 'ip pim sparse-mode' from all interfaces."
+ print "3) Remove IP addresses from all interfaces."
+ print "4) Remove all configured Loopback interfaces."
+ print "5) Remove all configured 'vrf context' except management."
+ print "6) Remove descriptions from all interfaces."
+ print "7) Run all of the above."
+ print "\nType any other key to exit menu."
+ print "-"*68
+
+ def remove_Feature(self):
+ # This function assumes all configured feature statements are comprised of 2 words.
+ # In the case of 'feature nv overlay', 3 words are used.
+ # To workaround this, explicitly remove 'feature nv overlay'.
+ cli('conf ; no feature nv overlay')
+ time.sleep(5) # wait 5 seconds for above command to get removed
+
+ #Now parse and iterate across output of 'show run | include feature'
+ show_run_feature = []
+ show_run_feature = cli('show run | inc feature')
+
+ feature = show_run_feature.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(1, len(feature) ,2):
+ cli_commands += " ; no feature " + feature[i]
+
+ if len(feature) == 0:
+ print "There are no features to remove."
+ else:
+ print "You are about to remove all 'feature' CLI statements."
+
+ confirm = raw_input("Are you sure? [y|n]")
+ if confirm == "y":
+ cli(cli_commands)
+ result = cli('show run | inc feature')
+ print result
+ print "All 'feature' CLI statements removed!\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+ def remove_Pim(self):
+ show_int_brief = []
+ show_int_brief = cli('show ip int brief | inc Eth|Lo')
+
+ interfaces = show_int_brief.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(0, len(interfaces) ,3):
+ cli_commands += " ; interface " + str(interfaces[i])
+ cli_commands += " ; no ip pim sparse-mode"
+
+ print "You are about to remove PIM sparse-mode under all interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+
+ if confirm == "y":
+ cli(cli_commands)
+ print "\nPIM successfully removed from all interfaces!\n"
+ print "Type 'show ip pim interface brief' to verify.\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+ def remove_Ipaddress(self):
+ show_int_brief = []
+ show_int_brief = cli('show ip int brief | inc Eth|Lo')
+
+ interfaces = show_int_brief.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(0, len(interfaces) ,3):
+ cli_commands += " ; interface " + str(interfaces[i])
+ cli_commands += " ; no ip address"
+
+ print "You are about to remove IP addresses from all interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+
+ if confirm == "y":
+ cli(cli_commands)
+ print "\nIP addresses successfully removed from all interfaces!\n"
+ print "Type 'show ip interface brief' to verify.\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+ def remove_Loopbacks(self):
+ show_int_brief = []
+ show_int_brief = cli('show int brief | inc Lo')
+
+ interfaces = show_int_brief.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(0, len(interfaces) ,3):
+ cli_commands += " ; no interface " + str(interfaces[i])
+
+ print "You are about to remove all Loopback interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+
+ if confirm == "y":
+ cli(cli_commands)
+ print "\nAll Loopback interfaces removed!\n"
+ print "Type 'show interface brief | inc Loopback' to verify.\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+ def remove_Vrf_Contexts(self):
+ show_run = []
+ show_run = cli('show run | include context | exclude management')
+
+ contexts = show_run.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(2, len(contexts) ,3):
+ cli_commands += " ; no vrf context " + str(contexts[i])
+ print "You are about to remove all vrf contexts (except management)."
+
+ confirm = raw_input("Are you sure? [y|n]")
+
+ if confirm == "y":
+ cli(cli_commands)
+ print "\nAll vrf contexts removed!\n"
+ print "Type 'show run | inc context' to verify.\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+ def remove_Interface_Descriptions(self):
+ show_int_brief = []
+ show_int_brief = cli('show int brief | json-pretty | inc interface | exc TABLE | exc ROW')
+ interfaces = show_int_brief.replace(',', '')
+ interfaces = interfaces.replace('"', '')
+
+ interfaces = interfaces.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(1, len(interfaces) ,2):
+ cli_commands += " ; interface " + str(interfaces[i] + " ; no description")
+
+ print "You are about to remove descriptions from all interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+
+ if confirm == "y":
+ cli(cli_commands)
+ print "\nRemoved descriptions from all interfaces!\n"
+ print "Type 'sh run | include description' to verify.\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+if __name__ == '__main__':
+ foo = Cleanup()
+ foo.print_Banner()
+ foo.print_Menu()
+ option = raw_input("\nSelect option [1-7]:")
+
+ if option == "1":
+ print "This may take some time..."
+ foo.remove_Feature()
+ elif option == "2":
+ check = cli('show feature | inc pim')
+ check_enabled = check.split()
+ if check_enabled[2] == "disabled":
+ print "There are no interfaces with 'ip pim sparse-mode' configured."
+ elif check_enabled[2] == "enabled":
+ foo.remove_Pim()
+ elif option == "3":
+ foo.remove_Ipaddress()
+ elif option == "4":
+ foo.remove_Loopbacks()
+ elif option == "5":
+ foo.remove_Vrf_Contexts()
+ elif option == "6":
+ foo.remove_Interface_Descriptions()
+ elif option == "7":
+ print "Checking configured features. This may take some time..."
+ foo.remove_Feature()
+ foo.remove_Ipaddress()
+ foo.remove_Loopbacks()
+ foo.remove_Pim()
+ foo.remove_Vrf_Contexts()
diff --git a/demo_scripts/find_freeip.py b/demo_scripts/find_freeip.py
new file mode 100644
index 00000000..2744a1f4
--- /dev/null
+++ b/demo_scripts/find_freeip.py
@@ -0,0 +1,72 @@
+"""
+ Cisco Nexus 9000 Switch On-Box script for finding Unused IP Addresses in the network
+"""
+
+import os,sys,re
+import json
+import argparse
+from cli import *
+
+"""
+Class to configure the required nexus switch and perform ping test
+"""
+
+class Args(object):
+
+ def __init__(self, args):
+ self.unused_ips = []
+ self.iprange = args.iprange
+ fullip = '.'.join(self.iprange.split('.')[:-1])
+ iprange = self.iprange.split('.')[-1].split("-")
+ self.ipseries = [fullip+"."+str(n) for n in range(int(iprange[0]), int(iprange[1])+1)]
+
+
+def print_banner():
+
+ msg = "*"*95
+ msg += '\n Cisco Nexus 9000 Switch On-Box script for finding Unused IP Addresses in the network.\n'
+ msg += '\nDeveloped By: OneCloud Consulting\n'
+ msg += 'Please contact info@1-cloud.net for any queries.\n\n'
+ msg += "*"*95
+ msg += "\n"
+ print msg
+
+def nexus_cli_deploy(params):
+ #execute the commands
+ cmd = "conf t" + ' ' + " ;" + ' ' + "interface loopback30" + ' ' + ";" + ' ' + "ip address "+params.ipseries[1]+"/32" + ' ' + ";"
+ cmd += ' ' + "interface loopback31" + ' ' + ";" + ' ' + "ip address "+params.ipseries[3]+"/32" + ' ' + ";" + ' ' + "exit" + ' ' + ";"
+ cli(cmd)
+
+
+def nexus_ping(params):
+ print " * Ping Test Starts *\n"
+ for ip in params.ipseries:
+ out = cli('ping %s count 1' % (ip))
+ m = re.search('([0-9\.]+)% packet loss',out)
+ print('%s - %s' % (ip, 'UP' if float(m.group(1)) == 0.0 else 'DOWN'))
+ if float(m.group(1)) != 0.0:
+ params.unused_ips.append(ip)
+ print "\n * Ping Test Completed *\n"
+
+ if len(params.unused_ips) > 0:
+ print "*"*95
+ print "\nFollowing IP Addresses are currently unused in your network:\n"
+ for ip in params.unused_ips:
+ print ip
+ print "*"*95
+
+def initialize_args():
+ parser = argparse.ArgumentParser(
+ description='To find Unused IP Addresses in the network',
+ epilog=""" """)
+ parser.add_argument('--iprange', '-ip', dest='iprange',
+ help='Please provide IP Address Range eg. 192.168.1.1-5', required=True)
+ args = parser.parse_args()
+ return Args(args)
+
+if __name__ == '__main__':
+ print_banner()
+ params = initialize_args()
+ nexus_cli_deploy(params)
+ nexus_ping(params)
+
diff --git a/demo_scripts/lldp.py b/demo_scripts/lldp.py
new file mode 100644
index 00000000..41050d63
--- /dev/null
+++ b/demo_scripts/lldp.py
@@ -0,0 +1,128 @@
+"""script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:On-Box
+:Title:Interface Description configuration
+:Short Description:To dynamically configure interface descriptions
+:Long Description:Check the LLDP state and modify the interface description accordingly.
+:Input:command to check the LLDP state and based on the command output,
+ modify the description of the interface
+:Output:interface description should be updated
+"""
+
+import os
+from cli import *
+import sys
+
+"""
+
+Class to update the interface description based on the
+LLDP state
+"""
+
+class Interface_Desc:
+
+ interface_message = {}
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+ versioncmd = "show version"
+ out = json.loads(clid(versioncmd))
+ chassis_id = out['chassis_id']
+ osversion = out['rr_sys_ver']
+ cpu_name = out['cpu_name']
+ memory = out['memory']
+ processor_board = out['proc_board_id']
+ device = out['host_name']
+ bootflash = out['bootflash_size']
+
+ print "Nexus Switch OS version is :" , osversion
+ print "Chassis ID is :", chassis_id
+ print cpu_name + "with" + str(memory) + "KB of memory"
+ print "Processor Board ID is " + processor_board
+
+ print "Host Name : " + device
+ print "Bootflash : " + str(bootflash) + ' ' + "KB"
+ print "\n"
+
+
+ def lldp_status(self):
+
+ intob = Interface_Desc()
+
+ #check lldp is enabled or not
+ lldp_stat = "show lldp neighbors"
+ try:
+ stat = json.loads(clid(lldp_stat))
+ except:
+ print "LLDP is not enabled on the host switch"
+ exit(1)
+ if (stat):
+ print "LLDP is enabled on the host switch"
+ lldp_nei = "show lldp neighbors"
+ status = json.loads(clid(lldp_nei))
+ #print status
+ status_list = status['TABLE_nbor']['ROW_nbor']
+ lldp_dict = {}
+
+ if (isinstance(status_list, list)):
+ for i in status_list:
+ for key,value in i.items():
+ if (key == 'chassis_id'):
+ lldp_dict.update({'device_id':value})
+ if (key == 'l_port_id'):
+ lldp_dict.update({'intf_id':value})
+ if (key == 'port_id'):
+ lldp_dict.update({key:value})
+ if (key == 'capability'):
+ lldp_dict.update({key:''})
+ intob.updateinterface(lldp_dict)
+
+ elif (isinstance(status_list, dict)):
+ for key,value in status_list.items():
+ if (key == 'chassis_id'):
+ lldp_dict.update({'device_id':value})
+ if (key == 'l_port_id'):
+ lldp_dict.update({'intf_id':value})
+ if (key == 'port_id'):
+ lldp_dict.update({key:value})
+ if (key == 'capability'):
+ lldp_dict.update({key:''})
+
+ intob.updateinterface(lldp_dict)
+ else:
+ print "Not implemented for this response type"
+
+ else:
+ print "LLDP is not enabled on the Host Switch."
+ exit(1)
+
+
+
+ #update the interface description
+ def updateinterface(self, data):
+ #print data
+ for key,value in data.iteritems():
+ if (key == 'intf_id'):
+ cmd1 = "interface" + ' ' + value
+ desc = "description" + ' ' + "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+ msg = "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+
+ cmd = "conf t" + ' ' + " ;" + ' ' + cmd1 + ' ' + ";" + ' ' + desc
+ cli(cmd)
+ print "\n"
+ print "Interface" + ' ' + data['intf_id'] + ' ' + "description is updated as : " + ' ' + msg
+ #if (data['capability']):
+ # print "Neighbor device" + ' ' + data['device_id'] + ' ' + "is capable as : "
+ #for i in data['capability']:
+ # print str(i)
+
+ # print data['capability']
+
+
+
+if __name__ == '__main__':
+ interfaceob = Interface_Desc()
+ interfaceob.nexus_version()
+ interfaceob.lldp_status()
+
diff --git a/demo_scripts/ospf.py b/demo_scripts/ospf.py
new file mode 100644
index 00000000..c3262fbd
--- /dev/null
+++ b/demo_scripts/ospf.py
@@ -0,0 +1,149 @@
+"""
+ Cisco Nexus 9000 Switch On-Box script for configuring
+ sparse-mode under all IP numbered interfaces.
+"""
+from cli import *
+
+class OspfInterface(object):
+
+ def __init__(self):
+ """ No variables are required for this class. """
+
+ def print_Banner(self):
+ msg = ' _ _ _ _ _ _ _ _ '
+ msg += '\n / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\'
+ msg += '\n ( O | S | P | F ) ( D | e | m | o )'
+ msg += '\n \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/'
+ msg += '\n\nCisco Nexus 9000 Switch On-Box script'
+ msg += '\nfor configuring OSPF interface attributes.'
+ msg += '\nDeveloped By: OneCloud Consulting\n'
+ msg += 'Please contact info@1-cloud.net for any queries.\n'
+ print msg
+
+ def print_Menu(self):
+ print "-"*30 + " Menu Options " + "-"*31
+ print "1) Configure 'ip router ospf 1 area 0.0.0.0' under all IP numbered interfaces."
+ print "2) Remove 'ip router ospf 1 area 0.0.0.0' from all IP numbered interfaces."
+ print "3) Configure 'ip router ospf cost 65535' under all IP numbered Ethernet interfaces."
+ print "4) Remove 'ip router ospf cost 65535' from all IP numbered Ethernet interfaces."
+ print "\nType any other key to exit menu."
+ print "-"*79
+
+ def configure_ospf_area(self):
+ show_int_brief = []
+ show_int_brief = cli('show ip int brief | inc Eth|Lo')
+
+ interfaces = show_int_brief.split( )
+
+ cli_commands = "conf ; router ospf 1"
+
+ for i in xrange(0, len(interfaces) ,3):
+ cli_commands += " ; interface " + str(interfaces[i])
+ cli_commands += " ; ip router ospf 1 area 0.0.0.0"
+
+ print "You are about to configure OSPF 1 (Area 0.0.0.0) under all IP numbered interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+
+ if confirm == "y":
+ cli(cli_commands)
+ result = cli('show ip ospf interface brief')
+ print result
+ print "OSPF process ID 1 (Area 0.0.0.0) enabled on all IP numbered interfaces!\n"
+ cli('show ip ospf int brief')
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+
+ def remove_ospf_area(self):
+ show_int_brief = []
+ show_int_brief = cli('show ip int brief | inc Eth|Lo')
+
+ interfaces = show_int_brief.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(0, len(interfaces) ,3):
+ cli_commands += " ; interface " + str(interfaces[i])
+ cli_commands += " ; no ip router ospf 1 area 0.0.0.0"
+
+ print "You are about to remove OSPF process ID 1 (Area 0.0.0.0) from all IP numbered interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+ if confirm == "y":
+ cli(cli_commands)
+ print "\nOSPF process ID 1 (Area 0.0.0.0) removed from all IP numbered interfaces!\n"
+ print "Type 'show ip ospf interface brief' to verify.\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+ def configure_ospf_cost(self):
+ show_int_brief = []
+ show_int_brief = cli('show ip int brief | inc Eth')
+
+ interfaces = show_int_brief.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(0, len(interfaces) ,3):
+ cli_commands += " ; interface " + str(interfaces[i])
+ cli_commands += " ; ip ospf cost 65535"
+
+ print "You are about to configure 'ip ospf cost 65535' under all IP numbered Ethernet interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+
+ if confirm == "y":
+ cli(cli_commands)
+ result = cli('show ip ospf interface brief')
+ print result
+ print "'ip ospf cost 65535' configured on all IP numbered Ethernet interfaces!\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+ def remove_ospf_cost(self):
+ show_int_brief = []
+ show_int_brief = cli('show ip int brief | inc Eth')
+
+ interfaces = show_int_brief.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(0, len(interfaces) ,3):
+ cli_commands += " ; interface " + str(interfaces[i])
+ cli_commands += " ; no ip ospf cost 65535"
+
+ print "You are about to remove 'ip ospf cost 65535' under all IP numbered Ethernet interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+
+ if confirm == "y":
+ cli(cli_commands)
+ result = cli('show ip ospf interface brief')
+ print result
+ print "'no ip ospf cost 65535' configured on all IP numbered Ethernet interfaces!\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+if __name__ == '__main__':
+ foo = OspfInterface()
+ foo.print_Banner()
+ foo.print_Menu()
+ option = raw_input("\nSelect option [1-4]:")
+
+ if option == "1":
+ foo.configure_ospf_area()
+ elif option == "2":
+ foo.remove_ospf_area()
+ elif option == "3":
+ foo.configure_ospf_cost()
+ elif option == "4":
+ foo.remove_ospf_cost()
diff --git a/demo_scripts/pim.py b/demo_scripts/pim.py
new file mode 100644
index 00000000..28d0e74c
--- /dev/null
+++ b/demo_scripts/pim.py
@@ -0,0 +1,89 @@
+"""
+ Cisco Nexus 9000 Switch On-Box script for configuring
+ sparse-mode under all IP numbered interfaces.
+"""
+from cli import *
+
+class Pim(object):
+
+ def __init__(self):
+ """ No variables are required for this class. """
+
+ def print_Banner(self):
+ msg = '\n _ _ _ _ _ _ _'
+ msg += '\n / \\ / \\ / \\ / \\ / \\ / \\ / \\'
+ msg += '\n ( P | I | M ) ( D | e | m | o )'
+ msg += '\n \\_/ \\_/ \\_/ \\_/ \\_/ \\_/ \\_/'
+ msg += '\n\nCisco Nexus 9000 Switch On-Box script'
+ msg += '\nfor configuring sparse-mode under all IP numbered interfaces.\n'
+ msg += '\nDeveloped By: OneCloud Consulting\n'
+ msg += 'Please contact info@1-cloud.net for any queries.\n'
+ print msg
+
+ def print_Menu(self):
+ print "-"*25 + " Menu Options " + "-"*25
+ print "1) Configure 'ip pim sparse-mode' under all IP numbered interfaces."
+ print "2) Remove 'ip pim sparse-mode' from all IP numbered interfaces."
+ print "\nType any other key to exit menu."
+ print "-"*68
+
+ def configure_Pim(self):
+ show_int_brief = []
+ show_int_brief = cli('show ip int brief | inc Eth|Lo')
+
+ interfaces = show_int_brief.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(0, len(interfaces) ,3):
+ cli_commands += " ; interface " + str(interfaces[i])
+ cli_commands += " ; ip pim sparse-mode"
+
+ print "You are about to configure PIM sparse-mode under all IP numbered interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+ if confirm == "y":
+ cli(cli_commands)
+ result = cli('show ip pim interface brief')
+ print result
+ print "PIM successfully enabled on all IP numbered interfaces!\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+ def remove_Pim(self):
+ show_int_brief = []
+ show_int_brief = cli('show ip int brief | inc Eth|Lo')
+
+ interfaces = show_int_brief.split( )
+
+ cli_commands = "conf"
+
+ for i in xrange(0, len(interfaces) ,3):
+ cli_commands += " ; interface " + str(interfaces[i])
+ cli_commands += " ; no ip pim sparse-mode"
+
+ print "You are about to remove PIM sparse-mode under all IP numbered interfaces."
+
+ confirm = raw_input("Are you sure? [y|n]")
+
+ if confirm == "y":
+ cli(cli_commands)
+ print "\nPIM successfully removed from all IP numbered interfaces!\n"
+ print "Type 'show ip pim interface brief' to verify.\n"
+ return
+ else:
+ print "You chose not to commit. Script aborted."
+ return
+
+if __name__ == '__main__':
+ foo = Pim()
+ foo.print_Banner()
+ foo.print_Menu()
+ option = raw_input("\nSelect option [1-2]:")
+
+ if option == "1":
+ foo.configure_Pim()
+ elif option == "2":
+ foo.remove_Pim()
diff --git a/demo_scripts/sh_int_count.py b/demo_scripts/sh_int_count.py
new file mode 100644
index 00000000..6f5a4c0c
--- /dev/null
+++ b/demo_scripts/sh_int_count.py
@@ -0,0 +1,85 @@
+"""
+ Cisco Nexus 9000 Switch On-Box script for monitoring interface RX counter.
+"""
+
+import os,sys,re
+import json
+import argparse
+import time
+from cli import *
+
+"""
+Class to configure the required nexus switch and monitor interface RX counter
+"""
+
+class Args(object):
+
+ def __init__(self, args):
+ self.interfacename = args.interfacename
+ self.nooftimes = args.nooftimes
+ self.delay = args.delay
+ self.log = args.log
+
+def print_banner(params, outfile):
+
+ msg = "*"*95
+ msg += '\n Cisco Nexus 9000 Switch On-Box script for Monitoring Interface RX Counter.\n'
+ msg += '\nDeveloped By: OneCloud Consulting\n'
+ msg += 'Please contact info@1-cloud.net for any queries.\n\n'
+ msg += "*"*95
+ msg += "\n"
+ print msg
+ if params.log == 'yes':
+ outfile.write(msg)
+
+def nexus_cli_deploy(params, outfile):
+ if int(params.nooftimes) > 0:
+ nooftimes = int(params.nooftimes)
+ else:
+ nooftimes = 1
+
+ if int(params.delay) > 0:
+ delay = int(params.delay)
+ else:
+ delay = 1
+
+ for i in range(nooftimes):
+ #execute the commands
+ msg = "Iteration No: "+str(i+1)
+ interface_data = json.loads(clid('show interface '+params.interfacename))
+ msg += "RX "+interface_data['TABLE_interface']['ROW_interface']['eth_inucast']+" packets\n"
+ print msg
+ if params.log == 'yes':
+ outfile.write(msg)
+ time.sleep(delay)
+
+
+def initialize_args():
+ parser = argparse.ArgumentParser(
+ description='To Monitor Interface RX Counter.',
+ epilog=""" """)
+ parser.add_argument('--interfacename', '-interface', dest='interfacename',
+ help='Name of the interface \"show interface name\" command should be executed', required=True)
+ parser.add_argument('--nooftimes', '-times', dest='nooftimes',
+ help='Number of times output should be displayed', required=True)
+ parser.add_argument('--delay', '-delay', dest='delay',
+ help='Time delay to monitor the Interface RX Counter', required=True)
+ parser.add_argument('--log', '-log', dest='log',
+ help='To write the output to file ', required=False)
+ args = parser.parse_args()
+ return Args(args)
+
+if __name__ == '__main__':
+ params = initialize_args()
+ outfile = ''
+ if params.log == 'yes':
+ shostname = json.loads(clid('show hostname'))
+ stime = json.loads(clid('show clock'))
+ filename = shostname['hostname']+'-'+stime['simple_time'].replace(' ','-')+'.log'
+ outfile = open(filename,'w')
+ print_banner(params,outfile)
+ nexus_cli_deploy(params,outfile)
+ if params.log == 'yes':
+ print "Output has been saved in the file named ("+filename+").\n"
+
+
diff --git a/demo_scripts/sh_proc_cpu_sort.py b/demo_scripts/sh_proc_cpu_sort.py
new file mode 100644
index 00000000..b3220a46
--- /dev/null
+++ b/demo_scripts/sh_proc_cpu_sort.py
@@ -0,0 +1,92 @@
+"""
+ Cisco Nexus 9000 Switch On-Box script for monitoring CPU usage.
+"""
+
+import os,sys,re
+import json
+import argparse
+import time
+from cli import *
+
+"""
+Class to configure the required nexus switch and monitor cpu usage
+"""
+
+class Args(object):
+
+ def __init__(self, args):
+ self.nooflines = args.nooflines
+ self.nooftimes = args.nooftimes
+ self.delay = args.delay
+ self.log = args.log
+
+def print_banner(params, outfile):
+
+ msg = "*"*95
+ msg += '\n Cisco Nexus 9000 Switch On-Box script for Monitoring CPU Usage.\n'
+ msg += '\nDeveloped By: OneCloud Consulting\n'
+ msg += 'Please contact info@1-cloud.net for any queries.\n\n'
+ msg += "*"*95
+ msg += "\n"
+ print msg
+ if params.log == 'yes':
+ outfile.write(msg)
+
+
+def nexus_cli_deploy(params, outfile):
+ pointer = 4
+ if int(params.nooflines) > 0:
+ nooflines = int(params.nooflines)+pointer
+ else:
+ nooflines = 5+pointer
+
+ if int(params.nooftimes) > 0:
+ nooftimes = int(params.nooftimes)
+ else:
+ nooftimes = 1
+
+ if int(params.delay) > 0:
+ delay = int(params.delay)
+ else:
+ delay = 1
+
+ for i in range(nooftimes):
+ #execute the commands
+ cmd = cli('show processes cpu sort')
+ cmdoutput = cmd.split('\n')
+ msg = "\n".join(s for s in cmdoutput[2:nooflines])
+ msg += "\n"
+ print msg
+ if params.log == 'yes':
+ outfile.write(msg)
+ time.sleep(delay)
+
+
+def initialize_args():
+ parser = argparse.ArgumentParser(
+ description='To Monitor CPU Usage.',
+ epilog=""" """)
+ parser.add_argument('--nooflines', '-lines', dest='nooflines',
+ help='Number of lines \"show processes cpu sort\" command should be executed', required=True)
+ parser.add_argument('--nooftimes', '-times', dest='nooftimes',
+ help='Number of times output should be displayed', required=True)
+ parser.add_argument('--delay', '-delay', dest='delay',
+ help='Time delay to monitor the CPU usage', required=True)
+ parser.add_argument('--log', '-log', dest='log',
+ help='To write the output to file ', required=False)
+ args = parser.parse_args()
+ return Args(args)
+
+if __name__ == '__main__':
+ params = initialize_args()
+ outfile = ''
+ if params.log == 'yes':
+ shostname = json.loads(clid('show hostname'))
+ stime = json.loads(clid('show clock'))
+ filename = shostname['hostname']+'-'+stime['simple_time'].replace(' ','-')+'.log'
+ outfile = open(filename,'w')
+ print_banner(params,outfile)
+ nexus_cli_deploy(params,outfile)
+ if params.log == 'yes':
+ print "Output has been saved in the file named ("+filename+").\n"
+
diff --git a/demo_scripts/sh_proc_mem.py b/demo_scripts/sh_proc_mem.py
new file mode 100644
index 00000000..88383fb5
--- /dev/null
+++ b/demo_scripts/sh_proc_mem.py
@@ -0,0 +1,91 @@
+"""
+ Cisco Nexus 9000 Switch On-Box script for monitoring process utilization.
+"""
+
+import os,sys,re
+import json
+import argparse
+import time
+from cli import *
+
+"""
+Class to configure the required nexus switch and monitor process utilization
+"""
+
+class Args(object):
+
+ def __init__(self, args):
+ self.nooflines = args.nooflines
+ self.nooftimes = args.nooftimes
+ self.delay = args.delay
+ self.log = args.log
+
+def print_banner(params, outfile):
+
+ msg = "*"*95
+ msg += '\n Cisco Nexus 9000 Switch On-Box script for Monitoring Process Utilization.\n'
+ msg += '\nDeveloped By: OneCloud Consulting\n'
+ msg += 'Please contact info@1-cloud.net for any queries.\n\n'
+ msg += "*"*95
+ msg += "\n"
+ print msg
+ if params.log == 'yes':
+ outfile.write(msg)
+
+def nexus_cli_deploy(params, outfile):
+ pointer = 3
+ if int(params.nooflines) > 0:
+ nooflines = int(params.nooflines)+pointer
+ else:
+ nooflines = 5+pointer
+
+ if int(params.nooftimes) > 0:
+ nooftimes = int(params.nooftimes)
+ else:
+ nooftimes = 1
+
+ if int(params.delay) > 0:
+ delay = int(params.delay)
+ else:
+ delay = 1
+
+ for i in range(nooftimes):
+ #execute the commands
+ cmd = cli('show processes memory')
+ cmdoutput = cmd.split('\n')
+ msg = "\n".join(s for s in cmdoutput[1:nooflines])
+ msg += "\n"
+ print msg
+ if params.log == 'yes':
+ outfile.write(msg)
+ time.sleep(delay)
+
+
+def initialize_args():
+ parser = argparse.ArgumentParser(
+ description='To Monitor Process Utilization.',
+ epilog=""" """)
+ parser.add_argument('--nooflines', '-lines', dest='nooflines',
+ help='Number of lines \"show processes memory\" command should be executed', required=True)
+ parser.add_argument('--nooftimes', '-times', dest='nooftimes',
+ help='Number of times output should be displayed', required=True)
+ parser.add_argument('--delay', '-delay', dest='delay',
+ help='Time delay to monitor the Process Utilization', required=True)
+ parser.add_argument('--log', '-log', dest='log',
+ help='To write the output to file ', required=False)
+ args = parser.parse_args()
+ return Args(args)
+
+if __name__ == '__main__':
+ params = initialize_args()
+ outfile = ''
+ if params.log == 'yes':
+ shostname = json.loads(clid('show hostname'))
+ stime = json.loads(clid('show clock'))
+ filename = shostname['hostname']+'-'+stime['simple_time'].replace(' ','-')+'.log'
+ outfile = open(filename,'w')
+ print_banner(params,outfile)
+ nexus_cli_deploy(params,outfile)
+ if params.log == 'yes':
+ print "Output has been saved in the file named ("+filename+").\n"
+
diff --git a/demo_scripts/sh_switch_details.py b/demo_scripts/sh_switch_details.py
new file mode 100644
index 00000000..696973da
--- /dev/null
+++ b/demo_scripts/sh_switch_details.py
@@ -0,0 +1,77 @@
+"""
+ Cisco Nexus 9000 Switch On-Box script for displaying given Switch details.
+"""
+
+import os,sys,re
+import json
+import argparse
+import time
+from cli import *
+
+"""
+Class to fetch Switch details
+"""
+
+class Args(object):
+
+ def __init__(self, args):
+ self.ip = args.ip
+ self.log = args.log
+
+def print_banner(params, outfile):
+
+ msg = "*"*95
+ msg += '\n Cisco Nexus 9000 Switch On-Box script for displaying given Switch details.\n'
+ msg += '\nDeveloped By: OneCloud Consulting\n'
+ msg += 'Please contact info@1-cloud.net for any queries.\n\n'
+ msg += "*"*95
+ msg += "\n"
+ print msg
+ if params.log == 'yes':
+ outfile.write(msg)
+
+def nexus_cli_deploy(params, outfile):
+
+ switch_data = json.loads(clid('show ip route '+params.ip))
+ try:
+ interface_data = switch_data['TABLE_vrf']['ROW_vrf']['TABLE_addrf']['ROW_addrf']['TABLE_prefix']['ROW_prefix']['TABLE_path']['ROW_path'][0]
+ if 'ifname' not in interface_data:
+ msg = "There is NO route for this IP address\n"
+ else:
+ switch_intdata = json.loads(clid('show cdp neighbors interface '+interface_data['ifname']+' detail'))
+ msg = "Device ID: "+switch_intdata['TABLE_cdp_neighbor_detail_info']['ROW_cdp_neighbor_detail_info']['device_id']+"\n"
+ msg += "System name: "+switch_intdata['TABLE_cdp_neighbor_detail_info']['ROW_cdp_neighbor_detail_info']['sysname']+"\n"
+ msg += "Platform: "+switch_intdata['TABLE_cdp_neighbor_detail_info']['ROW_cdp_neighbor_detail_info']['platform_id']+"\n"
+ msg += "Version: "+switch_intdata['TABLE_cdp_neighbor_detail_info']['ROW_cdp_neighbor_detail_info']['version']+"\n"
+ msg += "Management Address: "+switch_intdata['TABLE_cdp_neighbor_detail_info']['ROW_cdp_neighbor_detail_info']['v4mgmtaddr']+"\n"
+ msg += "\n"
+ except KeyError, e:
+ msg = "There is NO route for this IP address\n"
+ print msg
+ if params.log == 'yes':
+ outfile.write(msg)
+
+def initialize_args():
+ parser = argparse.ArgumentParser(
+ description='To Fetch Switch Details.',
+ epilog=""" """)
+ parser.add_argument('--ip', '-ip', dest='ip',
+ help='Please enter the Switch IP', required=True)
+ parser.add_argument('--log', '-log', dest='log',
+ help='To write the output to file ', required=False)
+ args = parser.parse_args()
+ return Args(args)
+
+if __name__ == '__main__':
+ params = initialize_args()
+ outfile = ''
+ if params.log == 'yes':
+ shostname = json.loads(clid('show hostname'))
+ stime = json.loads(clid('show clock'))
+ filename = shostname['hostname']+'-'+stime['simple_time'].replace(' ','-')+'.log'
+ outfile = open(filename,'w')
+ print_banner(params,outfile)
+ nexus_cli_deploy(params,outfile)
+ if params.log == 'yes':
+ print "Output has been saved in the file named ("+filename+").\n"
+
diff --git a/demo_scripts/sh_version.py b/demo_scripts/sh_version.py
new file mode 100644
index 00000000..18243973
--- /dev/null
+++ b/demo_scripts/sh_version.py
@@ -0,0 +1,103 @@
+"""
+ Nexus Switch Off-Box script for checking switch version.
+"""
+
+import os
+import sys
+import requests
+import json
+import argparse
+import csv
+from collections import namedtuple
+
+"""
+Class to configure the required nexus switch
+"""
+def pprinttable(rows):
+ if len(rows) > 0:
+ headers = rows[0]._fields
+ lens = []
+ for i in range(len(rows[0])):
+ lens.append(len(max([x[i] for x in rows] + [headers[i]],key=lambda x:len(str(x)))))
+ formats = []
+ hformats = []
+ for i in range(len(rows[0])):
+ if isinstance(rows[0][i], int):
+ formats.append("%%%dd" % lens[i])
+ else:
+ formats.append("%%-%ds" % lens[i])
+ hformats.append("%%-%ds" % lens[i])
+ pattern = " | ".join(formats)
+ hpattern = " | ".join(hformats)
+ separator = "-+-".join(['-' * n for n in lens])
+ print hpattern % tuple(headers)
+ print separator
+ for line in rows:
+ print pattern % tuple(line)
+ print separator
+
+
+class Nexus_Fetch_Version:
+
+ myheaders = {'content-type':'application/json-rpc'}
+ headers = {'content-type':'application/json'}
+
+ def __init__(self):
+ self.hostlist = []
+ self.hostversion = ''
+ parser = argparse.ArgumentParser()
+ parser.add_argument("version", help="provide version to check",type=str)
+ self.args = parser.parse_args()
+ self.Row = namedtuple('Row',['Host','IP_Address','Version','Matched'])
+
+ def print_banner(self):
+ msg = "*"*95
+ msg += '\n Cisco Nexus 9000 Switch Off-Box script for checking switch version.\n'
+ msg += '\nDeveloped By: OneCloud Consulting\n'
+ msg += 'Please contact info@1-cloud.net for any queries.\n\n'
+ msg += "*"*95
+ msg += "\n"
+ print msg
+ print "Expected Switch Version : "+self.args.version
+
+ def nexus_cli_deploy(self,host,ipaddress,username,password):
+
+ url = "http://"+ipaddress+"/ins"
+ #execute the commands
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show version","version":1},"id":1},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Fetch_Version.myheaders,auth=(username,password)).json()
+ self.hostversion = response['result']['body']['kickstart_ver_str']
+ if self.args.version == self.hostversion:
+ msg = "Success"
+ else:
+ msg = "Version not matched"
+ except Exception as e:
+ msg = "Error: Check Connectivity/Login/Feature NXAPI"
+ pass
+ self.hostlist.append(self.Row(host,ipaddress,self.hostversion,msg))
+
+ def print_result(self):
+ print "\n"
+ pprinttable(self.hostlist)
+ print "\n"
+
+if __name__ == '__main__':
+ ob = Nexus_Fetch_Version()
+ ob.print_banner()
+ try:
+ with open('Nexus_Login_Info.csv') as csvfile:
+ reader = csv.DictReader(csvfile)
+ for row in reader:
+ ob.nexus_cli_deploy(row['Device_Name'],row['IP_Address'],row['Username'],row['Password'])
+ except IOError:
+ print "Nexus_Login_Info.csv file not found and not able to read"
+ print "Make sure that csv file name must be Nexus_Login_Info.csv by default with the below mentioned format"
+ print "\n"
+ SRow = namedtuple('SRow',['Device_Name','IP_Address','Username','Password'])
+ sample = SRow('','','','')
+ pprinttable([sample])
+ print "\n"
+ sys.exit(0)
+ ob.print_result()
+
diff --git a/demo_vxlan/N9k-Leaf-1.txt b/demo_vxlan/N9k-Leaf-1.txt
new file mode 100644
index 00000000..b671e9b9
--- /dev/null
+++ b/demo_vxlan/N9k-Leaf-1.txt
@@ -0,0 +1,88 @@
+! Management IPAddress 10.1.1.3
+nv overlay evpn
+feature ospf
+feature pim
+feature bgp
+feature interface-vlan
+feature nv overlay
+feature vn-segment-vlan-based
+router ospf 1
+router-id 3.3.3.3
+ip pim rp-address 100.1.1.1 group-list 225.0.0.0/8
+ip pim ssm range 232.0.0.0/8
+interface loopback0
+ip address 3.3.3.3/32
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+interface ethernet 1/47
+no shutdown
+no switchport
+ip address 192.169.1.1/30
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+interface ethernet 1/48
+no shutdown
+no switchport
+ip address 192.169.1.5/30
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+interface ethernet 1/1
+switchport
+switchport access vlan 303
+no shutdown
+vrf context vrf_tenant_1
+vni 4900
+rd auto
+address-family ipv4 unicast
+route-target import 39000:39000 evpn
+route-target export 39000:39000 evpn
+route-target both auto evpn
+vlan 3900
+name l3-vni-vlan-for-vrf_tenant_1
+vn-segment 39000
+no shutdown
+interface vlan3900
+description l3-vni-for-vrf_tenant_1-routing
+no shutdown
+vrf member vrf_tenant_1
+ip forward
+vlan 303
+no shutdown
+vn-segment 200303
+evpn
+vni 200303 l2
+rd auto
+route-target import auto
+route-target export auto
+interface vlan303
+no shutdown
+vrf member vrf_tenant_1
+ip address 1.1.3.254/24
+fabric forwarding mode anycast-gateway
+fabric forwarding anycast-gateway-mac 0000.2222.3333
+interface nve1
+no shutdown
+source-interface loopback0
+host-reachability protocol bgp
+member vni 39000 associate-vrf
+member vni 200303
+suppress-arp
+mcast-group 225.1.1.3
+router bgp 65535
+router-id 3.3.3.3
+neighbor 10.1.1.1 remote-as 65535
+update-source loopback0
+address-family ipv4 unicast
+send-community both
+address-family l2vpn evpn
+send-community extended
+neighbor 10.1.1.1 remote-as 65535
+update-source loopback0
+address-family ipv4 unicast
+send-community both
+address-family l2vpn evpn
+send-community extended
+vrf vrf_tenant_1
+address-family ipv4 unicast
+no advertise l2vpn evpn
+advertise l2vpn evpn
diff --git a/demo_vxlan/N9k-Leaf-2.txt b/demo_vxlan/N9k-Leaf-2.txt
new file mode 100644
index 00000000..56ba95b0
--- /dev/null
+++ b/demo_vxlan/N9k-Leaf-2.txt
@@ -0,0 +1,88 @@
+! Management IPAddress 10.1.1.4
+nv overlay evpn
+feature ospf
+feature pim
+feature bgp
+feature interface-vlan
+feature nv overlay
+feature vn-segment-vlan-based
+router ospf 1
+router-id 4.4.4.4
+ip pim rp-address 100.1.1.1 group-list 225.0.0.0/8
+ip pim ssm range 232.0.0.0/8
+interface loopback0
+ip address 4.4.4.4/32
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+interface ethernet 1/47
+no shutdown
+no switchport
+ip address 192.169.2.1/30
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+interface ethernet 1/48
+no shutdown
+no switchport
+ip address 192.169.2.5/30
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+interface ethernet 1/1
+switchport
+switchport access vlan 303
+no shutdown
+vrf context vrf_tenant_1
+vni 4900
+rd auto
+address-family ipv4 unicast
+route-target import 39000:39000 evpn
+route-target export 39000:39000 evpn
+route-target both auto evpn
+vlan 3900
+name l3-vni-vlan-for-vrf_tenant_1
+vn-segment 39000
+no shutdown
+interface vlan3900
+description l3-vni-for-vrf_tenant_1-routing
+no shutdown
+vrf member vrf_tenant_1
+ip forward
+vlan 303
+no shutdown
+vn-segment 200303
+evpn
+vni 200303 l2
+rd auto
+route-target import auto
+route-target export auto
+interface vlan303
+no shutdown
+vrf member vrf_tenant_1
+ip address 1.1.3.254/24
+fabric forwarding mode anycast-gateway
+fabric forwarding anycast-gateway-mac 0000.2222.3333
+interface nve1
+no shutdown
+source-interface loopback0
+host-reachability protocol bgp
+member vni 39000 associate-vrf
+member vni 200303
+suppress-arp
+mcast-group 225.1.1.3
+router bgp 65535
+router-id 4.4.4.4
+neighbor 10.1.1.1 remote-as 65535
+update-source loopback0
+address-family ipv4 unicast
+send-community both
+address-family l2vpn evpn
+send-community extended
+neighbor 10.1.1.1 remote-as 65535
+update-source loopback0
+address-family ipv4 unicast
+send-community both
+address-family l2vpn evpn
+send-community extended
+vrf vrf_tenant_1
+address-family ipv4 unicast
+no advertise l2vpn evpn
+advertise l2vpn evpn
diff --git a/demo_vxlan/N9k-Spine-1.txt b/demo_vxlan/N9k-Spine-1.txt
new file mode 100644
index 00000000..57fd03ef
--- /dev/null
+++ b/demo_vxlan/N9k-Spine-1.txt
@@ -0,0 +1,56 @@
+! Management IPAddress 10.1.1.1
+nv overlay evpn
+feature ospf
+feature pim
+feature bgp
+feature interface-vlan
+feature nv overlay
+feature vn-segment-vlan-based
+router ospf 1
+router-id 10.1.1.1
+ip pim rp-address 100.1.1.1 group-list 225.0.0.0/8
+ip pim rp-candidate loopback301 group-list 225.0.0.0/8
+ip pim anycast-rp 100.1.1.1 10.1.1.1
+ip pim ssm range 232.0.0.0/8
+interface loopback0
+ip address 10.1.1.1/32
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+interface loopback301
+ip address 100.1.1.1/32
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+interface ethernet 1/1
+no shutdown
+no switchport
+ip address 192.169.1.2/30
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+interface ethernet 1/2
+no shutdown
+no switchport
+ip address 192.169.2.2/30
+ip router ospf 1 area 0.0.0.0
+ip pim sparse-mode
+router bgp 65535
+router-id 10.1.1.1
+neighbor 3.3.3.3 remote-as 65535
+update-source loopback0
+address-family ipv4 unicast
+send-community both
+route-reflector-client
+address-family l2vpn evpn
+send-community both
+route-reflector-client
+neighbor 4.4.4.4 remote-as 65535
+update-source loopback0
+address-family ipv4 unicast
+send-community both
+route-reflector-client
+address-family l2vpn evpn
+send-community both
+route-reflector-client
+vrf vrf_tenant_1
+address-family ipv4 unicast
+no advertise l2vpn evpn
+advertise l2vpn evpn
diff --git a/nexusscripts/off-box/cleanup/nexus_cleanup.cfg b/nexusscripts/off-box/cleanup/nexus_cleanup.cfg
new file mode 100644
index 00000000..1b7924bc
--- /dev/null
+++ b/nexusscripts/off-box/cleanup/nexus_cleanup.cfg
@@ -0,0 +1,11 @@
+[HostDetails]
+#Nexus Switch ipaddress and user details
+ipaddress=10.1.150.145
+username=admin
+password=#cisco123
+
+[BulkHostDetails]
+#Bulk Nexus Switch ipaddress and user details
+HostDetails={1:{'ipaddress':"10.1.150.145",'username':"admin",'password':"#cisco12"},
+ 2:{'ipaddress':"10.1.150.146",'username':"admin",'password':"#cisco12"},
+ }
diff --git a/nexusscripts/off-box/cleanup/nexus_cleanup.py b/nexusscripts/off-box/cleanup/nexus_cleanup.py
new file mode 100644
index 00000000..99e70a72
--- /dev/null
+++ b/nexusscripts/off-box/cleanup/nexus_cleanup.py
@@ -0,0 +1,420 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Cleanup
+:Box Type:Off-Box
+:Title:Nexus Configuration Cleanup
+:Short Description:To clean up the switch configurations
+:Long Description: Cleanup the switch configurations
+:Input:command to disable the configurations
+:Output:Nexus switch is cleaned up
+"""
+
+import os
+import requests
+import json
+import ConfigParser
+import datetime
+import time
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nexus_cleanup.cfg')
+
+ipaddress = config.get('HostDetails', 'ipaddress')
+username = config.get('HostDetails', 'username')
+password = config.get('HostDetails', 'password')
+
+#check the configuration details
+if (ipaddress == ''):
+ print "Please update the configuration file with Switch IPAddress"
+ exit(1)
+
+if ((username and password) == ''):
+ print "Please update the configuration file with Switch User Credentials"
+ exit(1)
+elif (username == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+elif (password == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+
+
+"""
+
+Class to cleanup the required nexus switch
+"""
+
+class Nexus_Clean:
+
+ myheaders = {'content-type':'application/json-rpc'}
+ headers = {'content-type':'application/json'}
+
+ url = "http://"+ipaddress+"/ins"
+
+
+ def nexus_clean(self):
+
+
+ #execute the commands
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"conf t","version":1},"id":1},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"no feature bash-shell","version":1},"id":2},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"terminal dont-ask","version":1},"id":3},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no feature scheduler","version":1},"id":4},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no int loo 5","version":1},"id":5},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no int loo 100","version":1},"id":6},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"defa int e 1/2 -3","version":1},"id":7},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"int e 1/2 -3","version":1},"id":8},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"shutdown","version":1},"id":9},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":10},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+#####################################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no onep","version":1},"id":1},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"chef","version":1},"id":2},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"no server https://chef-server.onecloudinc.com:443","version":1},"id":3},
+ ]
+
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no vrf management","version":1},"id":4},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no validation-client-name chef-validator","version":1},"id":5},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no interval 60","version":1},"id":6},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ cmd = "no node-name" + '' + ipaddress
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":cmd,"version":1},"id":7},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no domain-name onecloudinc.com","version":1},"id":8},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no name-server 10.1.150.254","version":1},"id":9},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+
+#####################################################################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"conf t","version":1},"id":1},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service chef","version":1},"id":2},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"no activate","version":1},"id":3},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":4},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no virtual-service chef","version":1},"id":5},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no chef","version":1},"id":6},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no scheduler job name helloworld","version":1},"id":7},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no scheduler name helloworld","version":1},"id":8},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+###########################################################################################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"puppet","version":1},"id":1},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no master puppet-master.sakommu-lab.com","version":1},"id":2},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no vrf management","version":1},"id":3},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no run-interval 60","version":1},"id":4},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no name-server 10.1.150.254","version":1},"id":5},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no activate","version":1},"id":6},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":7},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+############################################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"conf t","version":1},"id":1},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service puppet","version":1},"id":2},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"no activate","version":1},"id":3},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":4},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no virtual-service puppet","version":1},"id":5},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no puppet","version":1},"id":6},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no event manager applet foo","version":1},"id":7},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service uninstall name chef","version":1},"id":8},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+###############################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no vlan 500 - 555","version":1},"id":1},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no ip prefix-list puppet-list seq 5 permit 192.168.0.0/16","version":1},"id":2},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no inter port 10","version":1},"id":3},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no ip access-list puppet-command-config","version":1},"id":4},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no ntp server 10.1.150.51 use-vrf management","version":1},"id":5},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no ntp server 10.1.150.52 use-vrf management","version":1},"id":6},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service uninstall name puppet","version":1},"id":7},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service uninstall name chef","version":1},"id":8},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"guestshell destroy","version":1},"id":1},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no virtual-service destroy","version":1},"id":2},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"defa int e 1/10","version":1},"id":3},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"defa int e 2/1","version":1},"id":4},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no int loo 99","version":1},"id":5},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"copy r s","version":1},"id":6},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":7},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"conf t","version":1},"id":8},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do delete bootflash:interface_rate.py","version":1},"id":9},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do del bootflash:pingrange.py","version":1},"id":10},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do del bootflash:scripts/helloworld.py","version":1},"id":11},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do del bootflash:int_change.py","version":1},"id":12},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do del bootflash:Int_Change.py","version":1},"id":13},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no terminal dont-ask","version":1},"id":14},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+
+#####################################
+# #
+# Validation Commands #
+# #
+#####################################
+
+ try:
+ payload={"ins_api":{"version": "1.0","type":"cli_show_ascii","chunk": "0","sid": "1","input": "sh run | inc chef","output_format": "json"}}
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload), headers=Nexus_Clean.headers,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload={"ins_api":{"version": "1.0","type":"cli_show_ascii","chunk": "0","sid": "1","input": "sh run | inc puppet","output_format": "json"}}
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload), headers=Nexus_Clean.headers,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload={"ins_api":{"version": "1.0","type":"cli_show_ascii","chunk": "0","sid": "1","input": "sh run | inc ntp","output_format": "json"}}
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload), headers=Nexus_Clean.headers,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"sh virtual-service list","version":1},"id":4},]
+ response = requests.post(Nexus_Clean.url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+ print "Script execution is Complete!!!"
+
+
+
+
+
+
+if __name__ == '__main__':
+ ob = Nexus_Clean()
+ ob.nexus_clean()
diff --git a/nexusscripts/off-box/cleanup/nexus_cleanup_bulk.py b/nexusscripts/off-box/cleanup/nexus_cleanup_bulk.py
new file mode 100644
index 00000000..70cce248
--- /dev/null
+++ b/nexusscripts/off-box/cleanup/nexus_cleanup_bulk.py
@@ -0,0 +1,440 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Cleanup
+:Box Type:Off-Box
+:Title:Nexus Configuration Cleanup
+:Short Description:To clean up the switch configurations
+:Long Description:Cleanup the switch configurations
+:Input:command to disable the configurations
+:Output:Nexus switch is cleaned up
+"""
+
+import os
+import requests
+import json
+import ConfigParser
+import datetime
+import time
+import ast
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nexus_cleanup.cfg')
+
+def CheckConfig(host, ipaddress, username, password):
+
+ #check the configuration details
+ if (ipaddress == ''):
+ print "Please update the configuration file with Switch IPAddress for Host"+str(host)
+ exit(1)
+
+ if ((username and password) == ''):
+ print "Please update the configuration file with Switch User Credentials for Host"+str(host)
+ exit(1)
+ elif (username == ''):
+ print "Please update the configuration file with Switch User Credentials for Host"+str(host)
+ exit(1)
+ elif (password == ''):
+ print "Please update the configuration file with Switch User Credentials for Host"+str(host)
+ exit(1)
+ print "-- Host"+str(host)+" configuration is valid"
+ return
+
+
+"""
+
+Class to cleanup the required nexus switch
+"""
+
+class Nexus_Clean:
+
+ myheaders = {'content-type':'application/json-rpc'}
+ headers = {'content-type':'application/json'}
+
+ def nexus_clean(self, host, ipaddress, username, password):
+ url = "http://"+ipaddress+"/ins"
+ print "-- Trying "+url
+
+
+ #execute the commands
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"conf t","version":1},"id":1},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"no feature bash-shell","version":1},"id":2},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"terminal dont-ask","version":1},"id":3},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no feature scheduler","version":1},"id":4},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no int loo 5","version":1},"id":5},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no int loo 100","version":1},"id":6},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"defa int e 1/2 -3","version":1},"id":7},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"int e 1/2 -3","version":1},"id":8},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"shutdown","version":1},"id":9},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":10},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+#####################################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no onep","version":1},"id":1},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"chef","version":1},"id":2},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"no server https://chef-server.onecloudinc.com:443","version":1},"id":3},
+ ]
+
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no vrf management","version":1},"id":4},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no validation-client-name chef-validator","version":1},"id":5},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no interval 60","version":1},"id":6},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ cmd = "no node-name" + '' + ipaddress
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":cmd,"version":1},"id":7},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no domain-name onecloudinc.com","version":1},"id":8},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no name-server 10.1.150.254","version":1},"id":9},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+
+#####################################################################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"conf t","version":1},"id":1},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service chef","version":1},"id":2},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"no activate","version":1},"id":3},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":4},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no virtual-service chef","version":1},"id":5},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no chef","version":1},"id":6},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no scheduler job name helloworld","version":1},"id":7},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no scheduler name helloworld","version":1},"id":8},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+###########################################################################################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"puppet","version":1},"id":1},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no master puppet-master.sakommu-lab.com","version":1},"id":2},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no vrf management","version":1},"id":3},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no run-interval 60","version":1},"id":4},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no name-server 10.1.150.254","version":1},"id":5},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no activate","version":1},"id":6},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":7},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+############################################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"conf t","version":1},"id":1},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service puppet","version":1},"id":2},
+ {"jsonrpc":"2.0","method":"cli","params":{"cmd":"no activate","version":1},"id":3},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":4},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no virtual-service puppet","version":1},"id":5},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no puppet","version":1},"id":6},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no event manager applet foo","version":1},"id":7},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service uninstall name chef","version":1},"id":8},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+###############################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no vlan 500 - 555","version":1},"id":1},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no ip prefix-list puppet-list seq 5 permit 192.168.0.0/16","version":1},"id":2},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no inter port 10","version":1},"id":3},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no ip access-list puppet-command-config","version":1},"id":4},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no ntp server 10.1.150.51 use-vrf management","version":1},"id":5},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no ntp server 10.1.150.52 use-vrf management","version":1},"id":6},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service uninstall name puppet","version":1},"id":7},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"virtual-service uninstall name chef","version":1},"id":8},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ time.sleep(60)
+ except Exception as e:
+ pass
+################################
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"guestshell destroy","version":1},"id":1},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no virtual-service destroy","version":1},"id":2},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"defa int e 1/10","version":1},"id":3},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"defa int e 2/1","version":1},"id":4},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no int loo 99","version":1},"id":5},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"copy r s","version":1},"id":6},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"exit","version":1},"id":7},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"conf t","version":1},"id":8},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do delete bootflash:interface_rate.py","version":1},"id":9},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do del bootflash:pingrange.py","version":1},"id":10},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do del bootflash:scripts/helloworld.py","version":1},"id":11},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do del bootflash:int_change.py","version":1},"id":12},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"do del bootflash:Int_Change.py","version":1},"id":13},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"no terminal dont-ask","version":1},"id":14},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+
+#####################################
+# #
+# Validation Commands #
+# #
+#####################################
+
+ try:
+ payload={"ins_api":{"version": "1.0","type":"cli_show_ascii","chunk": "0","sid": "1","input": "sh run | inc chef","output_format": "json"}}
+ response = requests.post(url,data=json.dumps(payload), headers=Nexus_Clean.headers,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload={"ins_api":{"version": "1.0","type":"cli_show_ascii","chunk": "0","sid": "1","input": "sh run | inc puppet","output_format": "json"}}
+ response = requests.post(url,data=json.dumps(payload), headers=Nexus_Clean.headers,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload={"ins_api":{"version": "1.0","type":"cli_show_ascii","chunk": "0","sid": "1","input": "sh run | inc ntp","output_format": "json"}}
+ response = requests.post(url,data=json.dumps(payload), headers=Nexus_Clean.headers,auth=(username,password)).json()
+ except Exception as e:
+ pass
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"sh virtual-service list","version":1},"id":4},]
+ response = requests.post(url,data=json.dumps(payload),headers=Nexus_Clean.myheaders,auth=(username,password)).json()
+ except Exception as e:
+ pass
+
+ print "Host"+str(host)+" is cleaned up!!!\n"
+
+
+
+if __name__ == '__main__':
+ Hostdetails = ast.literal_eval(config.get('BulkHostDetails', 'HostDetails'))
+
+ print "*"*50
+ print " Intilizing Configuration check"
+ print "*"*50+"\n"
+
+ for host in Hostdetails:
+ ipaddress = Hostdetails[host]['ipaddress']
+ username = Hostdetails[host]['username']
+ password = Hostdetails[host]['password']
+ CheckConfig(host, ipaddress, username, password)
+
+ print "\n Finished Configuration check\n"
+
+ print "*"*50
+ print " Intilizing Host clean up"
+ print "*"*50+"\n"
+
+ for host in Hostdetails:
+ ipaddress = Hostdetails[host]['ipaddress']
+ username = Hostdetails[host]['username']
+ password = Hostdetails[host]['password']
+ ob = Nexus_Clean()
+ ob.nexus_clean(host, ipaddress, username, password)
+ print "Host"+str(host)+" is cleaned up!!!\n"
diff --git a/nexusscripts/off-box/cleanup/nexus_delbootflash.py b/nexusscripts/off-box/cleanup/nexus_delbootflash.py
new file mode 100644
index 00000000..d94a45d3
--- /dev/null
+++ b/nexusscripts/off-box/cleanup/nexus_delbootflash.py
@@ -0,0 +1,71 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Cleanup
+:Box Type:Off-Box
+:Title:Nexus Configuration Cleanup
+:Short Description:To delete the switch bootflash configurations
+:Long Description:Delete the switch bootflash configurations
+:Input:command to delete the configurations
+:Output:Nexus switch is cleaned up from bootflash scripts
+
+"""
+
+import os
+import requests
+import json
+import ConfigParser
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nexus_cleanup.cfg')
+
+ipaddress = config.get('HostDetails', 'ipaddress')
+username = config.get('HostDetails', 'username')
+password = config.get('HostDetails', 'password')
+
+#check the configuration details
+if (ipaddress == ''):
+ print "Please update the configuration file with Switch IPAddress"
+ exit(1)
+
+if ((username and password) == ''):
+ print "Please update the configuration file with Switch User Credentials"
+ exit(1)
+elif (username == ''):
+ print "Please update the configuration file with Switch User Creentials "
+ exit(1)
+elif (password == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+
+"""
+Delete Bootflash script
+
+"""
+
+class Nexus_DelBootFlash:
+
+ myheaders = {'content-type':'application/json-rpc'}
+
+ url = "http://"+ipaddress+"/ins"
+
+
+ def nexus_delbootflash(self):
+
+
+ #execute the commands
+
+ payload=[{"jsonrpc": "2.0","method": "cli","params": {"cmd": "conf t","version": 1},"id": 1},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "terminal dont-ask","version": 1},"id": 2},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "delete bootflash:scripts","version": 1},"id": 3}]
+ response = requests.post(Nexus_DelBootFlash.url,data=json.dumps(payload), headers=Nexus_DelBootFlash.myheaders,auth=(username,password)).json()
+ print response
+
+
+
+if __name__ == '__main__':
+ ob = Nexus_DelBootFlash()
+ ob.nexus_delbootflash()
+
+
+
diff --git a/nexusscripts/off-box/config-mgmt/README.md b/nexusscripts/off-box/config-mgmt/README.md
new file mode 100644
index 00000000..db706aa2
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/README.md
@@ -0,0 +1,31 @@
+
+#Nexus 9000 Switch Automation tasks
+
+#Automation of Switch Configuration Category
+Pre-requisites: Install jinja2 template engine e.g pip install jinja2
+Python version > 2.7.*
+
+Scripts are tested on Ubuntu 14.04 release machine.
+Nexus Switch version is NXOS: version 6.1(2)I3(1)
+
+Note: If pip does not exist then install it with the command 'sudo apt-get install python-pip'
+
+1. Dynamically update Interface description(for cdp protocol)
+
+ Steps :
+
+ a. Edit the nexus_automation.cfg configuration file with switch host details i.e username,password and email address.
+ b. verify the jinja templates exists or not.
+ c. schedule the cron job for the python script e.g */15 * * * * cd /home/ubuntu/nexus9000/nexusscripts && python interface_desc_cdp.py
+
+ Note : Follow the above steps to update interface description based on the lldp protocol status.
+
+
+2. FEX Configuration
+
+ Steps :
+
+ a. Configuration file is reused from the interface description update (check the host details and email address)
+ b. verify the jinja templates exists or not.
+ c. Example inputs to the script : --interface-type ethernet --interface-number 1/20 --fex-number 102
+ d. schedule the cron job for the python script e.g */15 * * * * cd /home/ubuntu/nexus9000/nexusscripts && python fex_config.py
diff --git a/nexusscripts/off-box/config-mgmt/fex_config.py b/nexusscripts/off-box/config-mgmt/fex_config.py
new file mode 100644
index 00000000..c3a33cfa
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/fex_config.py
@@ -0,0 +1,299 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:Off-Box
+:Title:FEX configuration
+:Short Description:To dynamically configure FEX
+:Long Description: Check the FEX state.If not installed,install the FEX.
+If not enabled ,enable the FEX.
+:Input:command to check the FEX installation and based on the command output,
+ install the FEX.Interfaces to be configured.
+:Output:FEX should be enabled and interfaces should be configured.
+"""
+
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+import os,sys
+import requests
+import json
+import ConfigParser
+import argparse
+import datetime
+
+from jinja2 import Template
+from jinja2 import Environment, FileSystemLoader
+
+PATH = os.getcwd()
+TEMPLATE_ENVIRONMENT = Environment(
+ autoescape=False,
+ loader=FileSystemLoader(os.path.join(PATH, 'templates')),
+ trim_blocks=False)
+
+
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nexus_automation.cfg')
+
+ipaddress = config.get('HostDetails', 'ipaddress')
+username = config.get('HostDetails', 'username')
+password = config.get('HostDetails', 'password')
+
+
+#list of to addresses for the email
+to_addresses = config.get('EmailDetails', 'to_addresses')
+
+#get the current working directory
+directory = os.getcwd()
+#html file and template location
+out_template = 'config_fex.jinja'
+out_html = directory+'/html/fex_'+ipaddress+'_.html'
+
+#remove the existing html file
+if (os.path.exists(out_html)):
+ os.remove(out_html)
+
+#check the configuration details
+if (ipaddress == ''):
+ print "Please update the configuration file with Switch IPAddress"
+ exit(1)
+
+if ((username and password) == ''):
+ print "Please update the configuration file with Switch User Credentials"
+ exit(1)
+elif (username == ''):
+ print "Please update the configuration file with Switch User Crdentials "
+ exit(1)
+elif (password == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+
+
+class Args(object):
+
+ def __init__(self, args):
+ self.interface_type = args.interface_type
+ self.interface_number = args.interface_number
+ self.fex_number = args.fex_number
+
+
+
+
+
+"""
+
+Class to install/enable FEX on the Nexus Switch
+"""
+
+class FEX_Config:
+
+ myheaders = {'content-type':'application/json-rpc'}
+
+ url = "http://"+ipaddress+"/ins"
+ earlierstat = ''; currentstat = '';
+ interface_list = [];
+
+ def render_template(self, template_filename, context):
+ return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
+
+
+ def initialize_args(self):
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 FEX configuration mgmt.',
+ epilog=""" """)
+
+ parser.add_argument('--interface-type', '-t', dest='interface_type',
+ help='Interface type',
+ choices={'ethernet', 'port-channel'})
+ parser.add_argument('--interface-number', '-s', dest='interface_number',
+ help="ethernet interface slot/port")
+ parser.add_argument('--fex-number', '-f', dest='fex_number',
+ help="fex number")
+
+ args = parser.parse_args()
+ return Args(args)
+
+
+
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+
+ global chassis_id, sys_version, hostname
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show version","version":1},"id":1},]
+ response = requests.post(FEX_Config.url,data=json.dumps(payload),headers=FEX_Config.myheaders,auth=(username,password)).json()
+ chassis_id = response['result']['body']['chassis_id']
+ sys_version = response['result']['body']['rr_sys_ver']
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show hostname","version":1},"id":1},]
+ response = requests.post(FEX_Config.url,data=json.dumps(payload),headers=FEX_Config.myheaders,auth=(username,password)).json()
+ hostname = response['result']['body']['hostname']
+
+
+ def fex_status(self):
+ fexob = FEX_Config()
+ global cdp_dict
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show feature-set fex","version":1},"id":1},]
+ response = requests.post(FEX_Config.url,data=json.dumps(payload),headers=FEX_Config.myheaders,auth=(username,password)).json()
+ #print response
+ status = response['result']['body']['TABLE-cfcFeatureSetTable']['cfcFeatureSetOpStatus']
+ FEX_Config.earlierstat = "On " + sys_version + " Nexus Switch FEX is " + status
+ print FEX_Config.earlierstat
+ fexob.fex_update(status)
+
+
+ def fex_update(self, stat):
+
+ if ((stat == 'disabled') or (stat == 'installed')) :
+ payload = [
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "conf t","version": 1},"id": 1},
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "feature-set fex","version": 1},"id": 2},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "exit","version": 1},"id": 2},
+
+ ]
+ response = requests.post(FEX_Config.url,data=json.dumps(payload),headers=FEX_Config.myheaders,auth=(username,password)).json()
+ FEX_Config.currentstat = "FEX is now enabled "
+ print FEX_Config.currentstat
+
+ if (stat == 'uninstalled') :
+ payload = [
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "conf t","version": 1},"id": 1},
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "install feature-set fex","version": 1},"id": 2},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "feature-set fex","version": 1},"id": 2},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "exit","version": 1},"id": 2},
+
+ ]
+ response = requests.post(FEX_Config.url,data=json.dumps(payload),headers=FEX_Config.myheaders,auth=(username,password)).json()
+ FEX_Config.currentstat = "FEX is installed and enabled"
+ print FEX_Config.currentstat
+
+
+ def fex_inter_config(self, params):
+
+ inter_cmd = "interface" + ' ' + params.interface_type + ' ' + params.interface_number
+ fex_cmd = "fex associate" + ' ' + params.fex_number
+ payload = [
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "conf t","version": 1},"id": 1},
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": inter_cmd,"version": 1},"id": 2},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "switchport","version": 1},"id": 3},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "switchport mode fex-fabric","version": 1},"id": 4},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": fex_cmd,"version": 1},"id": 5},
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "exit","version": 1},"id": 6},
+
+ ]
+
+
+ response = requests.post(FEX_Config.url,data=json.dumps(payload),headers=FEX_Config.myheaders,auth=(username,password)).json()
+ #print response
+ run_once = 0;
+ for i in response:
+ if (run_once == 0):
+ for key,value in i.items():
+ if (key == 'error'):
+ for k,v in value.items():
+ if (k == 'message'):
+ print v + ".Interface " + params.interface_type + ' ' + params.interface_number + ' ' + "is not configured to FEX.Check the Interface and FEX numbers are valid."
+ run_once = run_once + 1;
+
+
+ payload = [
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "show interface fex-fabric","version": 1},"id": 1},
+ ]
+ response = requests.post(FEX_Config.url,data=json.dumps(payload),headers=FEX_Config.myheaders,auth=(username,password)).json()
+
+ print "Configured Interfaces to FEX :"
+ status = response['result']['body']['TABLE_fex_fabric']['ROW_fex_fabric']
+ if (isinstance(status, list)):
+ for i in status:
+ for key,value in i.items():
+ if (key == 'fbr_port'):
+ print value
+ FEX_Config.interface_list.append(value)
+ elif (isinstance(status, dict)):
+ for key,value in status.items():
+ if (key == 'fbr_port'):
+ print value
+ FEX_Config.interface_list.append(value)
+ else:
+ print "Not implemented for this response type"
+
+
+
+
+
+ #update the jinja template with the data
+ def updatetemp(self):
+ systemob = FEX_Config()
+ templateVars = { "title" : "Nexus Switch Configuration management",
+ "description" : "FEX Configuration",
+ "chassis_id" : chassis_id,
+ "os_version" : sys_version,
+ "hostname" : hostname,
+ "earlierstat" : FEX_Config.earlierstat,
+ "currentstat" : FEX_Config.currentstat,
+ "interface_list" : FEX_Config.interface_list
+ }
+ with open(out_html, 'a') as f:
+ outputText = systemob.render_template(out_template, templateVars)
+ f.write(outputText)
+
+
+ def send_mail(self):
+
+ #account setup
+ username = 'nexus9000.adm@gmail.com';
+ password = '!cisco123';
+ server = 'smtp.gmail.com:587';
+ timestamp = datetime.datetime.now()
+
+ msg = MIMEMultipart()
+ msg['From'] = username
+ msg['To'] = to_addresses
+ msg['Subject'] = 'Nexus 9000 FEX Configuration Email' + ' ' + 'on' + ' ' + timestamp.strftime("%d/%m/%Y") + '@' + timestamp.strftime("%H:%M:%S")
+
+ fp = open(out_html, 'rb')
+ content = fp.read()
+ part = MIMEText(content, 'html')
+
+ msg.attach(part)
+
+ try:
+ mailserver = smtplib.SMTP(server)
+ # identify ourselves to smtp gmail client
+ mailserver.ehlo()
+ # secure our email with tls encryption
+ mailserver.starttls()
+ # re-identify ourselves as an encrypted connection
+ mailserver.ehlo()
+ mailserver.login(username, password)
+
+ mailserver.sendmail(msg['From'],(msg['To'].split(',')),msg.as_string())
+
+ mailserver.quit()
+ print "Successfully sent email"
+
+ except Exception:
+ print "Error: unable to send email"
+
+
+
+
+
+
+if __name__ == '__main__':
+ systemob = FEX_Config()
+ params = systemob.initialize_args()
+ systemob.nexus_version()
+ systemob.fex_status()
+ systemob.fex_inter_config(params)
+ systemob.updatetemp()
+ systemob.send_mail()
diff --git a/nexusscripts/off-box/config-mgmt/html/fex_10.1.150.12_.html b/nexusscripts/off-box/config-mgmt/html/fex_10.1.150.12_.html
new file mode 100644
index 00000000..82082e6b
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/html/fex_10.1.150.12_.html
@@ -0,0 +1,52 @@
+
+
+
+
+
+ Nexus Switch Configuration management
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : Nexus9000 C9396PX Chassis
+
OS Version : 6.1(2)I3(1)
+
+
+
+
+
+
+
Status | Updated Status |
+
+
+
+
+
+
+ |
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/config-mgmt/html/int_transciever_10.1.150.12_.html b/nexusscripts/off-box/config-mgmt/html/int_transciever_10.1.150.12_.html
new file mode 100644
index 00000000..04d8cdfe
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/html/int_transciever_10.1.150.12_.html
@@ -0,0 +1,139 @@
+
+
+
+
+
+ Nexus Switch Configuration management
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : Nexus9000 C9396PX Chassis
+
OS Version : 7.0(3)I1(1)
+
HOSTNAME : N9K-Standalone-Pod-2
+
IP Address : 10.1.150.12
+
+
+
+
+
+
+
Interface | Updated Transceiver Speed |
+
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/config-mgmt/html/interfacedesc_10.1.150.12_.html b/nexusscripts/off-box/config-mgmt/html/interfacedesc_10.1.150.12_.html
new file mode 100644
index 00000000..f990db5d
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/html/interfacedesc_10.1.150.12_.html
@@ -0,0 +1,56 @@
+
+
+
+
+
+ Nexus Switch System monitoring
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : Nexus9000 C9396PX Chassis
+
OS Version : 6.1(2)I3(1)
+
+
+
+
+
+
+
Interface | Updated Description |
+
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/config-mgmt/interface_desc_cdp.py b/nexusscripts/off-box/config-mgmt/interface_desc_cdp.py
new file mode 100644
index 00000000..2fa737d1
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/interface_desc_cdp.py
@@ -0,0 +1,251 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:Off-Box
+:Title:Interface Description configuration
+:Short Description:To dynamically configure interface descriptions
+:Long Description:Check the CDP state and modify the interface description accordingly.
+:Input:command to check the CDP state and based on the command output,
+ modify the description of the interface
+:Output:interface description should be updated
+"""
+
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+import os
+import requests
+import json
+import ConfigParser
+import datetime
+
+from jinja2 import Template
+from jinja2 import Environment, FileSystemLoader
+
+PATH = os.getcwd()
+TEMPLATE_ENVIRONMENT = Environment(
+ autoescape=False,
+ loader=FileSystemLoader(os.path.join(PATH, 'templates')),
+ trim_blocks=False)
+
+
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nexus_automation.cfg')
+
+ipaddress = config.get('HostDetails', 'ipaddress')
+username = config.get('HostDetails', 'username')
+password = config.get('HostDetails', 'password')
+
+#list of to addresses for the email
+to_addresses = config.get('EmailDetails', 'to_addresses')
+
+#get the current working directory
+directory = os.getcwd()
+#html file and template location
+out_template = 'update_interfacedesc.jinja'
+out_html = directory+'/html/interfacedesc_'+ipaddress+'_.html'
+
+#remove the existing html file
+if (os.path.exists(out_html)):
+ os.remove(out_html)
+
+#check the configuration details
+if (ipaddress == ''):
+ print "Please update the configuration file with Switch IPAddress"
+ exit(1)
+
+if ((username and password) == ''):
+ print "Please update the configuration file with Switch User Credentials"
+ exit(1)
+elif (username == ''):
+ print "Please update the configuration file with Switch User Creentials "
+ exit(1)
+elif (password == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+
+
+"""
+
+Class to update the interface description based on the
+CDP state
+"""
+
+class Interface_Desc:
+
+ myheaders = {'content-type':'application/json-rpc'}
+
+ url = "http://"+ipaddress+"/ins"
+ interface_message = {}
+ status = '';
+
+ def render_template(self, template_filename, context):
+ return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
+
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+
+ global chassis_id, sys_version, hostname
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show version","version":1},"id":1},]
+ response = requests.post(Interface_Desc.url,data=json.dumps(payload),headers=Interface_Desc.myheaders,auth=(username,password)).json()
+ chassis_id = response['result']['body']['chassis_id']
+ sys_version = response['result']['body']['rr_sys_ver']
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show hostname","version":1},"id":1},]
+ response = requests.post(Interface_Desc.url,data=json.dumps(payload),headers=Interface_Desc.myheaders,auth=(username,password)).json()
+ hostname = response['result']['body']['hostname']
+
+
+ def cdp_status(self):
+ intob = Interface_Desc()
+
+ #check CDP is enabled or not
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show cdp global","version":1},"id":1},]
+ response = requests.post(Interface_Desc.url,data=json.dumps(payload),headers=Interface_Desc.myheaders,auth=(username,password)).json()
+
+ if (response['result']['body']['cdp_global_enabled'] == 'enabled'):
+ print "CDP is enabled on the Host Switch"
+
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show cdp nei","version":1},"id":1},]
+ response = requests.post(Interface_Desc.url,data=json.dumps(payload),headers=Interface_Desc.myheaders,auth=(username,password)).json()
+ status_list = response['result']['body']['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info']
+ cdp_dict = {}
+
+ #print status_list
+
+
+ if (isinstance(status_list, list)):
+ for i in status_list:
+ for key,value in i.items():
+ if (key == 'device_id'):
+ cdp_dict.update({key:value})
+ if (key == 'intf_id'):
+ cdp_dict.update({key:value})
+ if (key == 'port_id'):
+ cdp_dict.update({key:value})
+ #if (key == 'capability'):
+ #print value
+ # cdp_dict.update({key:value})
+ intob.updateinterface(cdp_dict)
+ elif (isinstance(status_list, dict)):
+ for key,value in status_list.items():
+ if (key == 'device_id'):
+ cdp_dict.update({key:value})
+ if (key == 'intf_id'):
+ cdp_dict.update({key:value})
+ if (key == 'port_id'):
+ cdp_dict.update({key:value})
+ #if (key == 'capability'):
+ #print value
+ # cdp_dict.update({key:value})
+ intob.updateinterface(cdp_dict)
+ else:
+ print "Not implemented for this response type"
+
+
+
+ else:
+ print "CDP is not enabled on the Host Switch. "
+ Interface_Desc.status = "CDP is not enabled on the Host Switch."
+ intob.updatetemp();
+ intob.send_mail()
+ exit(1)
+
+
+
+
+
+ #update the interface description
+ def updateinterface(self, data):
+
+
+
+ for key,value in data.iteritems():
+ if (key == 'intf_id'):
+ cmd1 = "interface" + ' ' + value
+ desc = "description" + ' ' + "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+ msg = "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+ Interface_Desc.interface_message.update({data['intf_id']:msg})
+ payload = [
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "conf t","version": 1},"id": 1},
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": cmd1,"version": 1},"id": 2},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": desc,"version": 1},"id": 2},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "exit","version": 1},"id": 2},
+
+ ]
+ response = requests.post(Interface_Desc.url,data=json.dumps(payload),headers=Interface_Desc.myheaders,auth=(username,password)).json()
+ print "\n"
+ print "Interface" + ' ' + data['intf_id'] + ' ' + "description is updated as : " + ' ' + msg
+ #if (data['capability']):
+ # print "Neighbor device" + ' ' + data['device_id'] + ' ' + "is capable as : "
+ # print (data['capability'])
+
+ #update the jinja template with the data
+ def updatetemp(self):
+ systemob = Interface_Desc()
+ # print Interface_Desc.interface_message
+ templateVars = { "title" : "Nexus Switch Configuration management",
+ "description" : "Dynamically Update Interface Description",
+ "chassis_id" : chassis_id,
+ "os_version" : sys_version,
+ "hostname" : hostname,
+ "status" : Interface_Desc.status,
+ "message" : Interface_Desc.interface_message
+ }
+ with open(out_html, 'a') as f:
+ outputText = systemob.render_template(out_template, templateVars)
+ f.write(outputText)
+
+
+ def send_mail(self):
+
+ #account setup
+ username = 'nexus9000.adm@gmail.com';
+ password = '!cisco123';
+ server = 'smtp.gmail.com:587';
+ timestamp = datetime.datetime.now()
+
+ msg = MIMEMultipart()
+ msg['From'] = username
+ msg['To'] = to_addresses
+ msg['Subject'] = 'Nexus 9000 Interface Description Update (CDP) Email' + ' ' + 'on' + ' ' + timestamp.strftime("%d/%m/%Y") + '@' + timestamp.strftime("%H:%M:%S")
+
+ fp = open(out_html, 'rb')
+ content = fp.read()
+ part = MIMEText(content, 'html')
+
+ msg.attach(part)
+
+ try:
+ mailserver = smtplib.SMTP(server)
+ # identify ourselves to smtp gmail client
+ mailserver.ehlo()
+ # secure our email with tls encryption
+ mailserver.starttls()
+ # re-identify ourselves as an encrypted connection
+ mailserver.ehlo()
+ mailserver.login(username, password)
+
+ mailserver.sendmail(msg['From'],(msg['To'].split(',')),msg.as_string())
+
+ mailserver.quit()
+ print "Successfully sent email"
+
+ except Exception:
+ print "Error: unable to send email"
+
+
+
+
+
+
+if __name__ == '__main__':
+ systemob = Interface_Desc()
+ systemob.nexus_version()
+ systemob.cdp_status()
+ systemob.updatetemp()
+ systemob.send_mail()
diff --git a/nexusscripts/off-box/config-mgmt/interface_desc_lldp.py b/nexusscripts/off-box/config-mgmt/interface_desc_lldp.py
new file mode 100644
index 00000000..a92a1235
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/interface_desc_lldp.py
@@ -0,0 +1,245 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:Off-Box
+:Title:Interface Description configuration
+:Short Description:To dynamically configure interface descriptions
+:Long Description:Check the CDP state and modify the interface description accordingly.
+:Input:command to check the CDP state and based on the command output,
+ modify the description of the interface
+:Output:interface description should be updated
+"""
+
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+import os
+import requests
+import json
+import ConfigParser
+import datetime
+
+from jinja2 import Template
+from jinja2 import Environment, FileSystemLoader
+
+PATH = os.getcwd()
+TEMPLATE_ENVIRONMENT = Environment(
+ autoescape=False,
+ loader=FileSystemLoader(os.path.join(PATH, 'templates')),
+ trim_blocks=False)
+
+
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nexus_automation.cfg')
+
+ipaddress = config.get('HostDetails', 'ipaddress')
+username = config.get('HostDetails', 'username')
+password = config.get('HostDetails', 'password')
+
+#list of to addresses for the email
+to_addresses = config.get('EmailDetails', 'to_addresses')
+
+#get the current working directory
+directory = os.getcwd()
+#html file and template location
+out_template = 'update_interfacedesc.jinja'
+out_html = directory+'/html/interfacedesc_'+ipaddress+'_.html'
+
+#remove the existing html file
+if (os.path.exists(out_html)):
+ os.remove(out_html)
+
+#check the configuration details
+if (ipaddress == ''):
+ print "Please update the configuration file with Switch IPAddress"
+ exit(1)
+
+if ((username and password) == ''):
+ print "Please update the configuration file with Switch User Credentials"
+ exit(1)
+elif (username == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+elif (password == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+
+
+"""
+
+Class to update the interface description based on the
+CDP state
+"""
+
+class Interface_Desc:
+
+ myheaders = {'content-type':'application/json-rpc'}
+
+ url = "http://"+ipaddress+"/ins"
+ interface_message = {}
+ status = '';
+
+ def render_template(self, template_filename, context):
+ return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
+
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+
+ global chassis_id, sys_version, hostname
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show version","version":1},"id":1},]
+ response = requests.post(Interface_Desc.url,data=json.dumps(payload),headers=Interface_Desc.myheaders,auth=(username,password)).json()
+ chassis_id = response['result']['body']['chassis_id']
+ sys_version = response['result']['body']['rr_sys_ver']
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show hostname","version":1},"id":1},]
+ response = requests.post(Interface_Desc.url,data=json.dumps(payload),headers=Interface_Desc.myheaders,auth=(username,password)).json()
+ hostname = response['result']['body']['hostname']
+
+
+ def lldp_status(self):
+
+ intob = Interface_Desc()
+
+
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show lldp neighbors","version":1},"id":1},]
+ response = requests.post(Interface_Desc.url,data=json.dumps(payload),headers=Interface_Desc.myheaders,auth=(username,password)).json()
+
+ if ('result' in response.keys()):
+ print "LLDP is enabled on the host switch"
+ #print response
+ status_list = response['result']['body']['TABLE_nbor']['ROW_nbor']
+ #print status_list
+ lldp_dict = {}
+
+ if (isinstance(status_list, list)):
+ for i in status_list:
+ for key,value in i.items():
+ if (key == 'chassis_id'):
+ lldp_dict.update({'device_id':value})
+ if (key == 'l_port_id'):
+ lldp_dict.update({'intf_id':value})
+ if (key == 'port_id'):
+ lldp_dict.update({key:value})
+ #if (key == 'capability'):
+ # lldp_dict.update({key:''})
+ intob.updateinterface(lldp_dict)
+
+ elif (isinstance(status_list, dict)):
+ for key,value in status_list.items():
+ if (key == 'chassis_id'):
+ lldp_dict.update({'device_id':value})
+ if (key == 'l_port_id'):
+ lldp_dict.update({'intf_id':value})
+ if (key == 'port_id'):
+ lldp_dict.update({key:value})
+ #if (key == 'capability'):
+ # lldp_dict.update({key:''})
+
+ intob.updateinterface(lldp_dict)
+ else:
+ print "Not implemented for this response type"
+
+
+ else:
+ print "LLDP is not enabled on the Host Switch. "
+ Interface_Desc.status = "LLDP is not enabled on the Host Switch."
+ intob.updatetemp();
+ intob.send_mail()
+
+ exit(1)
+
+
+
+ #update the interface description
+ def updateinterface(self, data):
+
+
+ for key,value in data.iteritems():
+ if (key == 'intf_id'):
+ cmd1 = "interface" + ' ' + value
+ desc = "description" + ' ' + "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+ msg = "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+ Interface_Desc.interface_message.update({data['intf_id']:msg})
+ payload = [
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "conf t","version": 1},"id": 1},
+
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": cmd1,"version": 1},"id": 2},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": desc,"version": 1},"id": 2},
+ {"jsonrpc": "2.0","method": "cli","params": {"cmd": "exit","version": 1},"id": 2},
+
+ ]
+ response = requests.post(Interface_Desc.url,data=json.dumps(payload),headers=Interface_Desc.myheaders,auth=(username,password)).json()
+ print "\n"
+ print "Interface" + ' ' + data['intf_id'] + ' ' + "description is updated as : " + ' ' + msg
+ #if (data['capability']):
+ # print "Neighbor device" + ' ' + data['device_id'] + ' ' + "is capable as : "
+ # print data['capability']
+
+ #update the jinja template with the data
+ def updatetemp(self):
+ systemob = Interface_Desc()
+ # print Interface_Desc.interface_message
+ templateVars = { "title" : "Nexus Switch Configuration management",
+ "description" : "Dynamically Update Interface Description",
+ "chassis_id" : chassis_id,
+ "os_version" : sys_version,
+ "hostname" : hostname,
+ "status" : Interface_Desc.status,
+ "message" : Interface_Desc.interface_message
+ }
+ with open(out_html, 'a') as f:
+ outputText = systemob.render_template(out_template, templateVars)
+ f.write(outputText)
+
+
+ def send_mail(self):
+
+ #account setup
+ username = 'nexus9000.adm@gmail.com';
+ password = '!cisco123';
+ server = 'smtp.gmail.com:587';
+ timestamp = datetime.datetime.now()
+
+ msg = MIMEMultipart()
+ msg['From'] = username
+ msg['To'] = to_addresses
+ msg['Subject'] = 'Nexus 9000 Interface Description Update (LLDP) Email' + ' ' + 'on' + ' ' + timestamp.strftime("%d/%m/%Y") + '@' + timestamp.strftime("%H:%M:%S")
+
+ fp = open(out_html, 'rb')
+ content = fp.read()
+ part = MIMEText(content, 'html')
+
+ msg.attach(part)
+
+ try:
+ mailserver = smtplib.SMTP(server)
+ # identify ourselves to smtp gmail client
+ mailserver.ehlo()
+ # secure our email with tls encryption
+ mailserver.starttls()
+ # re-identify ourselves as an encrypted connection
+ mailserver.ehlo()
+ mailserver.login(username, password)
+
+ mailserver.sendmail(msg['From'],(msg['To'].split(',')),msg.as_string())
+
+ mailserver.quit()
+ print "Successfully sent email"
+
+ except Exception:
+ print "Error: unable to send email"
+
+
+
+
+
+
+if __name__ == '__main__':
+ interfaceob = Interface_Desc()
+ interfaceob.nexus_version()
+ interfaceob.lldp_status()
+ interfaceob.updatetemp()
+ interfaceob.send_mail()
diff --git a/nexusscripts/off-box/config-mgmt/l2_vlan_mgmt.py b/nexusscripts/off-box/config-mgmt/l2_vlan_mgmt.py
new file mode 100644
index 00000000..9250d95f
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/l2_vlan_mgmt.py
@@ -0,0 +1,201 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:Off-Box
+:Title:VLAN Configuration Management
+:Short Description:This script is to perform L2 VLAN operations
+:Long Description:This script is to perform configuration operations
+ of L2 VLAN interfaces
+:Input:N9K Address, username, password, L2 VLAN parameters
+:Output:status/result of the L2 VLAN configuration parameters
+"""
+
+import argparse
+import getpass
+import sys
+
+sys.path.append("../../../nx-os/nxapi/utils")
+from nxapi_utils import *
+from xmltodict import *
+
+cmd_config_terminal = "config terminal ;"
+cmd_int_ethernet = "interface ethernet %s/%s ;"
+cmd_int_port_channel = "interface port-channel %s ;"
+cmd_int_no_shutdown = "no shutdown ;"
+cmd_switchport_mode = "switchport mode %s ;"
+cmd_switchport_access_vlan = "switchport access vlan %s ;"
+cmd_switchport = "switchport ;"
+cmd_switchport_host = "switchport host ;"
+cmd_switchport_trunk_native = "switchport trunk native vlan %s ;"
+cmd_switchport_trunk_allowed_vlan = "switchport trunk allowed vlan %s %s ;"
+cmd_default_int = "default interface int-if %s ;"
+cmd_switchport_autostate_exclude = "switchport autostate exclude ;"
+cmd_switchport_autostate_exclude_vlan =\
+ "switchport autostate exclude vlan %s ;"
+cmd_svi_autostate_disable = "system default interface-vlan no autostate ;"
+
+cmd_vlan_tag_native = "vlan dot1q tag native ;"
+cmd_sys_default_port_mode_2_l2 = "system default switchport ;"
+
+cmd_copy_running_startup = "copy running-config startup-config ;"
+cmd_show_interface = "show running-config interface %s %s ;"
+
+class Args(object):
+
+ def __init__(self, args):
+ self.n9k = args.hostname
+ self.username = args.username
+ self.password = args.password
+ if not self.password:
+ self.password = getpass.getpass()
+ self.vlan_list = args.vlan_list
+ self.int_type = args.int_type
+ self.port_channel_id = args.port_channel_id
+ self.slot = args.slot
+ self.port = args.port
+ self.switchport_mode = args.switchport_mode
+ self.trunk_allowed_vlan_oper = args.trunk_allowed_vlan_oper
+ self.trunk_native_id = args.trunk_native_id
+ self.tag_native_vlan = args.tag_native_vlan
+
+
+def check_show_status(dict_res):
+
+ if dict_res['ins_api']['outputs']['output']['code'] == '200' and \
+ dict_res['ins_api']['outputs']['output']['msg'] == 'Success':
+ print dict_res['ins_api']['outputs']['output']['body']
+ return True
+ else:
+ print 'Error Msg:' + dict_res['ins_api']['outputs']['output']['msg']
+ print 'Code:' + dict_res['ins_api']['outputs']['output']['code']
+ return False
+
+
+def check_status(dict_res):
+ print dict_res
+ for output in dict_res['ins_api']['outputs']['output']:
+ if output['code'] == '200' and \
+ output['msg'] == 'Success':
+ print output['body']
+ else:
+ print 'Error Msg:' + output['msg']
+ print 'Code:' + output['code']
+ return False
+ return True
+
+
+def initialize_nxapi_handler(params):
+
+ thisNXAPI = NXAPI()
+ thisNXAPI.set_target_url('http://' + params.n9k +'/ins')
+ thisNXAPI.set_username(params.username)
+ thisNXAPI.set_password(params.password)
+ thisNXAPI.set_msg_type('cli_conf')
+ return thisNXAPI
+
+
+def create_l2_interface(params, nxapi_handler):
+
+ cmd_str = cmd_config_terminal
+ if params.tag_native_vlan:
+ cmd_str += cmd_vlan_tag_native
+
+ if params.int_type == 'ethernet':
+ cmd_str += cmd_int_ethernet % (params.slot, params.port)
+ if params.int_type == 'port-channel':
+ cmd_str += cmd_int_port_channel % (params.port_channel_id)
+
+ cmd_str += cmd_switchport
+
+ if params.switchport_mode == 'access':
+ cmd_str += cmd_switchport_mode % (params.switchport_mode)
+ cmd_str += cmd_switchport_access_vlan % (params.vlan_list)
+ elif params.switchport_mode == 'host':
+ cmd_str += cmd_switchport_host
+ elif params.switchport_mode == 'trunk':
+ cmd_str += cmd_switchport_mode % (params.switchport_mode)
+ if params.trunk_native_id:
+ cmd_str += cmd_switchport_trunk_native % (params.trunk_native_id)
+ if params.trunk_allowed_vlan_oper in {'add', 'remove', 'except'}:
+ cmd_str += cmd_switchport_trunk_allowed_vlan %\
+ (params.trunk_allowed_vlan_oper, params.vlan_list)
+ elif params.trunk_allowed_vlan_oper in {'all', 'none'}:
+ cmd_str += cmd_switchport_trunk_allowed_vlan %\
+ (params.trunk_allowed_vlan_oper, ' ')
+ else:
+ cmd_str += cmd_switchport_trunk_allowed_vlan %\
+ (params.vlan_list, ' ')
+
+ cmd_str += cmd_int_no_shutdown
+ cmd_str += cmd_copy_running_startup
+
+ print cmd_str
+ nxapi_handler.set_cmd(cmd_str)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def show_interface(params, nxapi_handler):
+ cmd_str = ''
+ if params.int_type == 'ethernet':
+ cmd_str += cmd_show_interface %\
+ (params.int_type, "%s/%s" %(params.slot, params.port))
+ elif params.int_type == 'port-channel':
+ cmd_str += cmd_show_interface % (params.int_type,\
+ params.port_channel_id)
+ print cmd_str
+ nxapi_handler.set_cmd(cmd_str)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_show_status(dict_res)
+
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 L2 VLAN interface configuration mgmt.',
+ epilog=""" """)
+
+ parser.add_argument('--n9k', '-a', dest='hostname',
+ help='Nexus 9XXX hostname or ip address', required=True)
+ parser.add_argument('--user', '-u', dest='username',
+ help='Username to login to Nexus 9XXX switch', required=True)
+ parser.add_argument('--password', '-c', dest='password',
+ help='Password to login to Nexus 9XXX switch')
+ parser.add_argument('--interface_type', '-t', dest='int_type',
+ help='Interface type',
+ choices={'ethernet', 'port-channel'})
+ parser.add_argument('--slot-id', '-s', dest='slot',
+ help="ethernet interface slot-id")
+ parser.add_argument('--port-id', '-p', dest='port',
+ help="ethernet interface port-id")
+ parser.add_argument('--port-channel-id', '-n', dest='port_channel_id',
+ help='port-channel id')
+ parser.add_argument('--switchport-mode', '-m', dest='switchport_mode',
+ help='switchport mode \'access|trunk|host\'',
+ choices={'access', 'trunk', 'host'})
+ parser.add_argument('--trunk-allowed-vlan-oper', '-o',
+ dest='trunk_allowed_vlan_oper', help='trunk allowed vlan oper',
+ choices={'add', 'remove', 'except', 'all', 'none'}),
+ parser.add_argument('--vlan-list', '-v', dest='vlan_list',
+ help='VLAN ID/list')
+ parser.add_argument('--trunk-native-vlan-id', '-k', dest='trunk_native_id',
+ help='Trunk native VLAN ID')
+ parser.add_argument('--tag-native-vlan-traffic', '-r',
+ dest='tag_native_vlan',
+ help='Tag native VLAN traffic', type=bool, default=False)
+
+ args = parser.parse_args()
+ return Args(args)
+
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+ nxapi_handler = initialize_nxapi_handler(params)
+ create_l2_interface(params, nxapi_handler)
+ show_interface(params, nxapi_handler)
+
+ exit(0)
diff --git a/nexusscripts/off-box/config-mgmt/l3_vlan_mgmt.py b/nexusscripts/off-box/config-mgmt/l3_vlan_mgmt.py
new file mode 100644
index 00000000..63631e97
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/l3_vlan_mgmt.py
@@ -0,0 +1,221 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:Off-Box
+:Title:VLAN Configuration Management
+:Short Description:This script is to perform L3 VLAN operations
+:Long Description:This script is to perform configuration operations
+ of L3 VLAN interfaces
+:Input:N9K Address, username, password, L3 VLAN parameters
+:Output:status/result of the L3 VLAN configuration parameters
+"""
+
+import argparse
+import getpass
+import sys
+
+sys.path.append("../../../nx-os/nxapi/utils")
+from nxapi_utils import *
+from xmltodict import *
+
+cmd_negate_option = "no"
+cmd_config_terminal = "config terminal ;"
+cmd_int_ethernet = "interface ethernet %s ;"
+cmd_int_no_shutdown = "no shutdown ;"
+cmd_no_switchport = "no switchport ;"
+cmd_feature_int_vlan = "feature interface-vlan ;"
+cmd_create_svi_int = "interface vlan %s ;"
+cmd_ip_addr_mask = "ip address %s %s ;"
+cmd_ip_addr_len = "ip address %s/%s ;"
+cmd_ipv6_addr_len = "ipv6 address %s/%s ;"
+cmd_ipv6_addr_link_local = "ipv6 address use-link-local-only ;"
+cmd_encap_dot1q_vlanid = "encapsulation dot1Q %s ;"
+cmd_show_interfaces = "show interfaces ;"
+
+cmd_int_port_channel = "interface port-channel %s ;"
+cmd_int_vlan_interface = "interface vlan %s ;"
+cmd_no_shutdown = "no shutdown ;"
+cmd_show_vlan_vlanid = "show interface vlan %s ;"
+cmd_create_loopback_int = "interface loopback %s ;"
+cmd_show_loopback_int = "show interface loopback %s ;"
+
+cmd_add_vrf_member = "vrf member %s ;"
+cmd_show_vrf = "show vrf %s interface %s %s ;"
+cmd_show_interface = "show interface %s %s ;"
+
+cmd_copy_running_startup = "copy running-config startup-config ;"
+
+
+
+class Args(object):
+
+ def __init__(self, args):
+ self.n9k = args.hostname
+ self.username = args.username
+ self.password = args.password
+ if not self.password:
+ self.password = getpass.getpass()
+
+ self.vlan_id = args.vlan_id
+ self.int_type = args.int_type
+ self.slot = args.slot
+ self.port = args.port
+ self.port_channel_id = args.port_channel_id
+ self.dot1q_vlanid = args.dot1q_vlanid
+ self.loopback_instance = args.loopback_instance
+ self.ip_addr = args.ip_addr
+ self.ip_len = args.ip_len
+ self.ip_mask = args.ip_mask
+ self.ipv6_addr = args.ipv6_addr
+ self.ipv6_len = args.ipv6_len
+ self.ipv6_link_local = args.ipv6_link_local
+ self.vrf_member = args.vrf_member
+
+
+def check_show_status(dict_res):
+
+ if dict_res['ins_api']['outputs']['output']['code'] == '200' and \
+ dict_res['ins_api']['outputs']['output']['msg'] == 'Success':
+ print dict_res['ins_api']['outputs']['output']['body']
+ return True
+ else:
+ print 'Error Msg:' + dict_res['ins_api']['outputs']['output']['msg']
+ print 'Code:' + dict_res['ins_api']['outputs']['output']['code']
+ return False
+
+
+def check_status(dict_res):
+ print dict_res
+ for output in dict_res['ins_api']['outputs']['output']:
+ if output['code'] == '200' and \
+ output['msg'] == 'Success':
+ print output['body']
+ else:
+ print 'Error Msg:' + output['msg']
+ print 'Code:' + output['code']
+ return False
+ return True
+
+
+def initialize_nxapi_handler(params):
+
+ thisNXAPI = NXAPI()
+ thisNXAPI.set_target_url('http://' + params.n9k +'/ins')
+ thisNXAPI.set_username(params.username)
+ thisNXAPI.set_password(params.password)
+ thisNXAPI.set_msg_type('cli_conf')
+ return thisNXAPI
+
+
+def create_l3_interface(params, nxapi_handler):
+
+ cmd_str = cmd_config_terminal
+ cmd_str += cmd_feature_int_vlan
+
+ if params.int_type == 'ethernet':
+ cmd_str += cmd_int_ethernet % (params.slot + "/" + params.port)
+ cmd_str += cmd_no_switchport
+ if params.dot1q_vlanid:
+ cmd_str += cmd_encap_dot1q_vlanid % (params.dot1q_vlanid)
+ elif params.int_type == 'port-channel':
+ cmd_str += cmd_int_port_channel % (params.port_channel_id)
+ cmd_str += cmd_encap_dot1q_vlanid % (params.dot1q_vlanid)
+ elif params.int_type == 'vlan':
+ cmd_str += cmd_int_vlan_interface % (params.vlan_id)
+ cmd_str += cmd_no_shutdown
+ elif params.int_type == 'loopback':
+ cmd_str += cmd_create_loopback_int % (params.loopback_instance)
+
+ if params.ip_addr and params.ip_len:
+ cmd_str += cmd_ip_addr_len % (params.ip_addr, params.ip_len)
+ elif params.ip_addr and params.ip_mask:
+ cmd_str += cmd_ip_addr_mask % (params.ip_addr, params.ip_mask)
+
+ if params.ipv6_addr and params.ipv6_len:
+ cmd_str += cmd_ipv6_addr_len % (params.ipv6_addr, params.ipv6_len)
+ if params.ipv6_link_local:
+ cmd_str += cmd_ipv6_addr_link_local
+
+ if params.vrf_member:
+ cmd_str += cmd_add_vrf_member % (params.vrf_member)
+
+ cmd_str += cmd_int_no_shutdown
+ cmd_str += cmd_copy_running_startup
+
+ print cmd_str
+ nxapi_handler.set_cmd(cmd_str)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def show_interface(params, nxapi_handler):
+ cmd_str = ''
+ if params.int_type == 'ethernet':
+ cmd_str += cmd_show_interface %\
+ (params.int_type, "%s/%s" %(params.slot, params.port))
+ elif params.int_type == 'port-channel':
+ cmd_str += cmd_show_interface % params.int_type, params.port_channel_id
+ elif params.int_type == 'vlan':
+ cmd_str += cmd_show_interface % params.int_type, params.vlan_id
+ elif params.int_type == 'loopback':
+ cmd_str += cmd_show_interface % params.int_type, params.loopback_instance
+ print cmd_str
+ nxapi_handler.set_cmd(cmd_str)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_show_status(dict_res)
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 L3 VLAN interface configuration mgmt.',
+ epilog=""" """)
+
+ parser.add_argument('--n9k', '-a', dest='hostname',
+ help='Nexus 9XXX hostname or ip address', required=True)
+ parser.add_argument('--user', '-u', dest='username',
+ help='Username to login to Nexus 9XXX switch', required=True)
+ parser.add_argument('--password', '-c', dest='password',
+ help='Password to login to Nexus 9XXX switch')
+ parser.add_argument('--interface_type', '-t', dest='int_type',
+ help='Interface type',
+ choices={'ethernet', 'port-channel', 'vlan', 'loopback'})
+ parser.add_argument('--slot-id', '-s', dest='slot',
+ help="ethernet interface slot-id")
+ parser.add_argument('--port-id', '-p', dest='port',
+ help="ethernet interface port-id")
+ parser.add_argument('--port-channel-id', '-n', dest='port_channel_id',
+ help='Encaptulation vlan-id')
+ parser.add_argument('--encap_vlanid', '-e', dest='dot1q_vlanid',
+ help='Encaptulation vlan-id')
+ parser.add_argument('--vlanid', '-v', dest='vlan_id',
+ help='VLAN id')
+ parser.add_argument('--loopback_instnace_id', '-o', dest='loopback_instance',
+ help='Loopback interface instance id')
+ parser.add_argument('--ip-address', '-4', dest='ip_addr',
+ help='IPv4 address')
+ parser.add_argument('--ip-address-length', '-l', dest='ip_len',
+ help='IPv4 address length')
+ parser.add_argument('--ip-address-mask', '-m', dest='ip_mask',
+ help='IPv4 address length')
+ parser.add_argument('--ipv6-address', '-6', dest='ipv6_addr',
+ help='IPv6 address')
+ parser.add_argument('--ipv6-address-length', '-k', dest='ipv6_len',
+ help='IPv6 address length')
+ parser.add_argument('--ipv6-use-link-local-address', '-q', dest='ipv6_link_local',
+ help='IPv6 address length', type=bool, default=False)
+ parser.add_argument('--vrf-member-id', '-r', dest='vrf_member',
+ help='IPv6 address length')
+
+ args = parser.parse_args()
+ return Args(args)
+
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+ nxapi_handler = initialize_nxapi_handler(params)
+ create_l3_interface(params, nxapi_handler)
+ show_interface(params, nxapi_handler)
+ exit(0)
diff --git a/nexusscripts/off-box/config-mgmt/nexus_automation.cfg b/nexusscripts/off-box/config-mgmt/nexus_automation.cfg
new file mode 100644
index 00000000..44d9477d
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/nexus_automation.cfg
@@ -0,0 +1,11 @@
+[HostDetails]
+#Nexus Switch ipaddress and user details
+ipaddress=
+username=
+password=
+
+
+[EmailDetails]
+#email to address list
+to_addresses=,
+
diff --git a/nexusscripts/off-box/config-mgmt/nx_automation.cfg b/nexusscripts/off-box/config-mgmt/nx_automation.cfg
new file mode 100644
index 00000000..64c829e8
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/nx_automation.cfg
@@ -0,0 +1,18 @@
+[DEFAULT]
+
+
+[HOSTS]
+# Switch IP address and login creds
+ipaddress = 10.1.150.12
+switchusername = admin
+switchpassword = !cisco123
+
+[FROM_EMAIL]
+# email creds to send the notifications
+from_address = nexus9000.adm@gmail.com
+mail_password = !cisco123
+server = smtp.gmail.com:587
+
+[EMAIL]
+# mail address to send the notification messages
+to_address = venkat@onecloudinc.com,darshan@onecloudinc.com,
diff --git a/nexusscripts/off-box/config-mgmt/templates/config_fex.jinja b/nexusscripts/off-box/config-mgmt/templates/config_fex.jinja
new file mode 100644
index 00000000..2cc3184a
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/templates/config_fex.jinja
@@ -0,0 +1,73 @@
+
+
+
+
+
+ {{ title }}
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : {{ chassis_id }}
+
OS Version : {{ os_version }}
+
Hostname : {{ hostname }}
+
+
+
+
+
+
+
Status | Updated Status |
+
+
+{% if earlierstat %}
+
+
+
+ |
+{%endif %}
+{%if currentstat %}
+
+
+ |
+
+{%else %}
+
+
+
+ |
+
+{%endif %}
+
+
+
+
+
+
+
+
+
+{%if interface_list %}
+
+{% for j in interface_list %}
+
+
+{% endfor %}
+{%endif %}
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/config-mgmt/templates/update_interfacedesc.jinja b/nexusscripts/off-box/config-mgmt/templates/update_interfacedesc.jinja
new file mode 100644
index 00000000..cd7e3ed7
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/templates/update_interfacedesc.jinja
@@ -0,0 +1,62 @@
+
+
+
+
+
+ {{ title }}
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : {{ chassis_id }}
+
OS Version : {{ os_version }}
+
Hostname : {{ hostname }}
+
+
+
+
+
+{% if status %}
+
+
{{ status }}
+{% endif %}
+
+
+
+
+
+
+{% if message %}
+
+
Interface | Updated Description |
+
+
+{% for key,value in message.items() %}
+
+
+
+
+
+ |
+
+
+ |
+
+{%endfor %}
+{% endif %}
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/config-mgmt/templates/update_intspeed.jinja b/nexusscripts/off-box/config-mgmt/templates/update_intspeed.jinja
new file mode 100644
index 00000000..5b3d41f0
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/templates/update_intspeed.jinja
@@ -0,0 +1,50 @@
+
+
+
+
+
+ {{ title }}
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : {{ chassis_id }}
+
OS Version : {{ os_version }}
+
HOSTNAME : {{ hostname }}
+
IP Address : {{ ipaddress }}
+
+
+
+
+
+
+
Interface | Updated Transceiver Speed |
+
+
+{% for key,value in message.items() %}
+
+
+
+ |
+
+
+ |
+
+{%endfor %}
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/config-mgmt/transceiver.py b/nexusscripts/off-box/config-mgmt/transceiver.py
new file mode 100644
index 00000000..b4c84e84
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/transceiver.py
@@ -0,0 +1,297 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:Off-Box
+:Title:Transceiver Auto-speed-configuration
+:Short Description:This script is to auto configure the transceiver speed at all the available interfaces of switch.
+:Long Description:Helps in configuring any changes in speed at any Interfaces of the switch by setting specific supported speed of the transceiver.
+:Input:No Input
+:Output:No Output
+"""
+
+from __future__ import print_function
+import requests
+import json
+import os
+import re
+import ConfigParser
+import datetime
+import smtplib
+import os.path
+#from __future__ import print_function
+from email.mime.application import MIMEApplication
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from jinja2 import Template
+from jinja2 import Environment, FileSystemLoader
+
+
+PATH = os.getcwd()
+TEMPLATE_ENVIRONMENT = Environment(
+ autoescape=False,
+ loader=FileSystemLoader(os.path.join(PATH, 'templates')),
+ trim_blocks=False)
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nx_automation.cfg')
+
+# Switch Host Details
+ipaddress = config.get('HOSTS', 'ipaddress')
+switchuser = config.get('HOSTS', 'switchusername')
+switchpassword = config.get('HOSTS', 'switchpassword')
+
+#list of to addresses for the email
+to_address = config.get('EMAIL', 'to_address')
+
+#get the current working directory
+directory = os.getcwd()
+#html file and template location
+out_template = 'update_intspeed.jinja'
+out_html = directory+'/html/int_transciever_'+ipaddress+'_.html'
+
+#remove the existing html file
+if os.path.exists(out_html):
+ os.remove(out_html)
+
+#check the configuration details
+if (ipaddress == ''):
+ print ("Please update the configuration file with Switch IPAddress")
+ exit(1)
+
+if ((switchuser and switchpassword) == ''):
+ print ("Please update the configuration file with Switch User Credentials")
+ exit(1)
+elif (switchuser == ''):
+ print ("Please update the configuration file with Switch User Credentials ")
+ exit(1)
+elif (switchpassword == ''):
+ print ("Please update the configuration file with Switch User Credentials ")
+ exit(1)
+
+
+class Interface_Config:
+
+ global url, myheaders
+
+ url='http://'+ipaddress+'/ins'
+
+ # Messege Header
+ myheaders={'content-type':'application/json-rpc'}
+ speed_dict = {}
+ interface_list = []
+
+ def render_template(self, template_filename, context):
+ return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
+
+
+ # Scroll around the interfaces to configure which interfaces have got transceivers and not
+ def interfaceconfig(self):
+ interfaceobj = Interface_Config()
+ global bitrate, status, hostname, chassis_id, sys_version
+
+
+ payload=[{ "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "configure terminal", "version": 1 }, "id": 1 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "feature nxapi", "version": 1 }, "id": 2 }]
+ requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+
+ # Get the Hostname
+ cmd = "show hostname"
+ payload=[{ "jsonrpc": "2.0", "method": "cli", "params": { "cmd": cmd, "version": 1 }, "id": 1 }]
+ response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+ hostname = response['result']['body']['hostname']
+
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show version","version":1},"id":1},]
+ response = requests.post(url,data=json.dumps(payload),headers=myheaders,auth=(switchuser,switchpassword)).json()
+ chassis_id = response['result']['body']['chassis_id']
+ sys_version = response['result']['body']['rr_sys_ver']
+
+ # Get the available interfaces from the device
+ cmd = "show interface status"
+ payload=[{ "jsonrpc": "2.0", "method": "cli", "params": { "cmd": cmd, "version": 1 }, "id": 1 }]
+ response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+ Interface_Config.interface_list = response['result']['body']['TABLE_interface']['ROW_interface']
+
+ for i in Interface_Config.interface_list:
+ for key,value in i.items():
+ if (key == 'interface'):
+ m = re.search('Ethernet(.*)', value)
+ if m:
+ found = m.group(1)
+ slotport = found.split('/')
+
+ cmd = "show interface ethernet"+str(slotport[0])+"/"+str(slotport[1])+"transceiver"
+ payload=[{ "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "show interface ethernet "+str(slotport[0])+"/"+str(slotport[1])+" transceiver", "version": 1 }, "id": 1 }]
+ response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+
+ status = response['result']['body']['TABLE_interface']['ROW_interface']['sfp']
+
+ # Check whether Transceiver is present or not at the interface
+ if (status == "present" ):
+ bitrate = response['result']['body']['TABLE_interface']['ROW_interface']['nom_bitrate']
+ interfaceobj.transceiver(slotport[0], slotport[1], bitrate);
+ else :
+ pass
+ interfaceobj.send_mail()
+
+ # Get the Nexus Transceiver info
+ def transceiver(self, i, j, bitrate):
+ interfaceobj = Interface_Config()
+ print ("\nAvailable Nominal bitrate/SFP speed at interface "+str(i)+"/"+str(j)+" = "+str(bitrate))
+
+ if (bitrate >= 100 and bitrate <= 1000):
+ payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "configure terminal", "version": 1 }, "id": 1 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "interface ethernet "+str(i)+"/"+str(j), "version": 1 }, "id": 2 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "speed 100", "version": 1 }, "id": 3 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "no shutdown", "version": 1 }, "id": 4 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "end", "version": 1 }, "id": 5 }]
+ out = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+ err = interfaceobj.error_chk(out)
+ if (err == 10):
+ interfaceobj.auto(i,j)
+ else :
+ interfaceobj.speed_dict["Ethernet"+str(i)+"/"+str(j)] = "Speed is set with "+str(bitrate)
+
+ elif (bitrate >= 1000 and bitrate <= 10000):
+ payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "configure terminal", "version": 1 }, "id": 1 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "interface ethernet "+str(i)+"/"+str(j), "version": 1 }, "id": 2 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "speed 1000", "version": 1 }, "id": 3 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "no shutdown", "version": 1 }, "id": 4 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "end", "version": 1 }, "id": 5 }]
+ out = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+ err = interfaceobj.error_chk(out)
+ if (err == 10):
+ interfaceobj.auto(i,j)
+ else :
+ interfaceobj.speed_dict["Ethernet"+str(i)+"/"+str(j)] = "Speed is set with "+str(bitrate)
+
+ elif (bitrate >= 10000 and bitrate <= 40000):
+ payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "configure terminal", "version": 1 }, "id": 1 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "interface ethernet "+str(i)+"/"+str(j), "version": 1 }, "id": 2 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "speed 10000", "version": 1 }, "id": 3 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "no shutdown", "version": 1 }, "id": 4 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "end", "version": 1 }, "id": 5 }]
+ out = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+ err = interfaceobj.error_chk(out)
+ if (err == 10):
+ interfaceobj.auto(i,j)
+ else :
+# key = "Ethernet"+str(i)+"/"+str(j)
+# value = "Speed is set with "+str(bitrate)
+ interfaceobj.speed_dict["Ethernet"+str(i)+"/"+str(j)] = "Speed is set with "+str(bitrate)
+
+ elif (bitrate >= 40000 and bitrate <= 100000):
+ payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "configure terminal", "version": 1 }, "id": 1 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "interface ethernet "+str(i)+"/"+str(j), "version": 1 }, "id": 2 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "speed 40000", "version": 1 }, "id": 3 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "no shutdown", "version": 1 }, "id": 4 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "end", "version": 1 }, "id": 5 }]
+ out = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+ err = interfaceobj.error_chk(out)
+ if (err == 10):
+ interfaceobj.auto(i,j)
+ else :
+ interfaceobj.speed_dict["Ethernet"+str(i)+"/"+str(j)] = "Speed is set with "+str(bitrate)
+
+ elif (bitrate >= 100000):
+ payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "configure terminal", "version": 1 }, "id": 1 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "interface ethernet "+str(i)+"/"+str(j), "version": 1 }, "id": 2 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "speed 100000", "version": 1 }, "id": 3 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "no shutdown", "version": 1 }, "id": 4 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "end", "version": 1 }, "id": 5 }]
+ out = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+ err = interfaceobj.error_chk(out)
+ if (err == 10):
+ interfaceobj.auto(i,j)
+ else :
+ interfaceobj.speed_dict["Ethernet"+str(i)+"/"+str(j)] = "Speed is set with "+str(bitrate)
+
+ else :
+ interfaceobj.auto(i,j)
+
+
+ def error_chk(self,out):
+ interfaceobj = Interface_Config()
+ ret_val = 0
+ for x in out:
+ for key,value in x.items():
+ if (key == 'error'):
+ for a,b in value.items():
+ if (a == 'data'):
+ for c,d in b.items():
+ if (c == 'msg'):
+ print (d.replace ("ERROR", "NOTE"), end = '')
+ print ("Transceiver value is set to an AUTO.")
+ ret_val=10
+ return ret_val
+
+
+ # Configure the interface speed to AUTO
+ def auto(self, i, j):
+ interfaceobj = Interface_Config()
+ payload=[{ "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "configure terminal", "version": 1 }, "id": 1 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "interface ethernet "+str(i)+"/"+str(j), "version": 1 }, "id": 2 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "speed auto", "version": 1 }, "id": 3 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "no shutdown", "version": 1 }, "id": 4 },
+ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "end", "version": 1 }, "id": 5 }]
+ out = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
+ interfaceobj.speed_dict["Ethernet"+str(i)+"/"+str(j)] = "Speed is set with AUTO."
+
+ #update the jinja template with the data
+ def updatetemp(self):
+ interfaceobj = Interface_Config()
+ templateVars = { "title" : "Nexus Switch Configuration management",
+ "description" : "Dynamically Update Interface Description",
+ "chassis_id" : chassis_id,
+ "os_version" : sys_version,
+ "hostname" : hostname,
+ "ipaddress" : ipaddress,
+ "message" : interfaceobj.speed_dict
+ }
+ with open(out_html, 'a') as f:
+ outputText = interfaceobj.render_template(out_template, templateVars)
+ f.write(outputText)
+ f.close()
+
+ # Notify the Admin about changes taken care at different interfaces.
+ def send_mail(self):
+
+ #account setup
+ username = 'nexus9000.adm@gmail.com';
+ password = '!cisco123';
+ server = 'smtp.gmail.com:587';
+ timestamp = datetime.datetime.now()
+
+ msg = MIMEMultipart()
+ msg['From'] = username
+ msg['To'] = to_address
+ msg['Subject'] = 'Transceiver speed updated at HOST: "' + hostname + '" with IP: ' + ipaddress + ' on ' + timestamp.strftime("%d/%m/%Y") + ' @ ' + timestamp.strftime("%H:%M:%S")
+ interfaceobj.updatetemp()
+ so = open(out_html,'r')
+ content = so.read()
+ so.close()
+ part = MIMEText(content, 'html')
+ msg.attach(part)
+ try:
+ mailserver = smtplib.SMTP(server);
+ # identify ourselves to smtp gmail client
+ mailserver.ehlo();
+ # secure our email with tls encryption
+ mailserver.starttls();
+ # re-identify ourselves as an encrypted connection
+ mailserver.ehlo();
+ mailserver.login(username, password);
+ mailserver.sendmail(msg['From'],(msg['To'].split(',')),msg.as_string());
+
+ mailserver.quit();
+ print ("\nSuccessfully sent email")
+ print ("")
+
+ except Exception:
+ print ("Error: unable to send email, please check your Internet connection.")
+ print ("")
+
+
+if __name__ == '__main__':
+ interfaceobj = Interface_Config()
+ interfaceobj.interfaceconfig()
diff --git a/nexusscripts/off-box/config-mgmt/vlan_config.py b/nexusscripts/off-box/config-mgmt/vlan_config.py
new file mode 100644
index 00000000..db0d8c3a
--- /dev/null
+++ b/nexusscripts/off-box/config-mgmt/vlan_config.py
@@ -0,0 +1,158 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:Off-Box
+:Title:VLAN Configuration Management
+:Short Description:This script is to perform VLAN operations
+:Long Description:This script is to perform configuration operations
+ of VLAN interfaces
+:Input:N9K Address, username, password, VLAN parameters
+:Output:status/result of the VLAN configuration parameters
+"""
+
+import argparse
+import getpass
+import sys
+
+sys.path.append("../../../nx-os/nxapi/utils")
+from nxapi_utils import *
+from xmltodict import *
+
+cmd_config_terminal = "config terminal ;"
+cmd_vlan_id_range = "vlan %s ;"
+cmd_no_vlan_id_range = "no vlan %s ;"
+cmd_vlan_media = "media enet ;"
+cmd_vlan_name = "name %s ;"
+cmd_vlan_state = "state %s ;"
+cmd_vlan_no_shutdown = "no shutdown ;"
+cmd_vlan_long_name = "system vlan long-name ;"
+
+cmd_copy_running_startup = "copy running-config startup-config ;"
+
+cmd_vlan_show = "show running-config vlan %s ;"
+cmd_vlan_summary = "show vlan summary ;"
+cmd_vtp_status = "show vtp status ;"
+
+
+class Args(object):
+
+ def __init__(self, args):
+ self.n9k = args.hostname
+ self.username = args.username
+ self.password = args.password
+ if not self.password:
+ self.password = getpass.getpass()
+
+ self.vlan = args.vlan
+ self.vlan_name = args.vlan_name
+ self.vlan_state = args.vlan_state
+ self.action = args.action
+ self.vlan_shutdown = args.vlan_shutdown
+
+
+def check_show_status(dict_res):
+
+ if dict_res['ins_api']['outputs']['output']['code'] == '200' and \
+ dict_res['ins_api']['outputs']['output']['msg'] == 'Success':
+ print dict_res['ins_api']['outputs']['output']['body']
+ return True
+ else:
+ print 'Error Msg:' + dict_res['ins_api']['outputs']['output']['msg']
+ print 'Code:' + dict_res['ins_api']['outputs']['output']['code']
+ return False
+
+
+def check_status(dict_res):
+
+ for output in dict_res['ins_api']['outputs']['output']:
+ if output['code'] == '200' and \
+ output['msg'] == 'Success':
+ print output['body']
+ else:
+ print 'Error Msg:' + output['msg']
+ print 'Code:' + output['code']
+ return False
+ return True
+
+
+def initialize_nxapi_handler(params):
+
+ thisNXAPI = NXAPI()
+ thisNXAPI.set_target_url('http://' + params.n9k +'/ins')
+ thisNXAPI.set_username(params.username)
+ thisNXAPI.set_password(params.password)
+ thisNXAPI.set_msg_type('cli_conf')
+ return thisNXAPI
+
+
+def configure_vlan(params, nxapi_handler):
+
+ cmd_str = cmd_config_terminal
+ if params.action == 'configure':
+ cmd_str += cmd_vlan_id_range % (params.vlan)
+ if params.vlan_name:
+ cmd_str += cmd_vlan_name % (params.vlan_name)
+ if params.vlan_state:
+ cmd_str += cmd_vlan_state % (params.vlan_state)
+ if not params.vlan_shutdown:
+ cmd_str += cmd_vlan_no_shutdown
+ elif params.action == 'remove':
+ cmd_str += cmd_no_vlan_id_range % (params.vlan)
+
+ cmd_str += cmd_copy_running_startup
+
+ print cmd_str
+ nxapi_handler.set_cmd(cmd_str)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def show_vlan(params, nxapi_handler):
+ cmd_str = cmd_vlan_show % (params.vlan)
+
+ print cmd_str
+ nxapi_handler.set_cmd(cmd_str)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_show_status(dict_res)
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 VLAN configuration',
+ epilog=""" """)
+
+ parser.add_argument('--n9k', '-a', dest='hostname',
+ help='Nexus 9XXX hostname or ip address', required=True)
+ parser.add_argument('--user', '-u', dest='username',
+ help='Username to login to Nexus 9XXX switch', required=True)
+ parser.add_argument('--password', '-c', dest='password',
+ help='Password to login to Nexus 9XXX switch')
+ parser.add_argument('--vlan', '-v', dest='vlan',
+ help='VLAN id/range', required=True)
+ parser.add_argument('--vlan-name', '-n', dest='vlan_name',
+ help='VLAN name')
+ parser.add_argument('--state', '-s', dest='vlan_state',
+ help='VLAN state', choices={'active', 'suspend'}, default='active')
+ parser.add_argument('--shutdown', '-d', dest='vlan_shutdown',
+ help='VLAN state', type=bool, default=False)
+ parser.add_argument('--action', '-o', dest='action',
+ help='VLAN state', choices={'configure', 'remove', 'show'})
+
+ args = parser.parse_args()
+ return Args(args)
+
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+ nxapi_handler = initialize_nxapi_handler(params)
+ if params.action in {'remove', 'configure'}:
+ configure_vlan(params, nxapi_handler)
+ show_vlan(params, nxapi_handler)
+ else:
+ show_vlan(params, nxapi_handler)
+
+ exit(0)
diff --git a/nexusscripts/off-box/monitoring/README.md b/nexusscripts/off-box/monitoring/README.md
new file mode 100644
index 00000000..74becd4f
--- /dev/null
+++ b/nexusscripts/off-box/monitoring/README.md
@@ -0,0 +1,29 @@
+
+#Nexus 9000 Switch Automation tasks
+
+#Automation of Switch Monitoring Category
+Pre-requisites: Install jinja2 template engine e.g pip install jinja2
+Python version > 2.7.*
+
+Scripts are tested on Ubuntu 14.04 release machine.
+Nexus Switch version is NXOS: version 6.1(2)I3(1)
+
+Note: If pip does not exist then install it with the command 'sudo apt-get install python-pip'
+
+1. Interface monitoring
+
+ Steps :
+
+ a. Edit the nexus_automation.cfg configuration file with switch host details and email address.
+ b. verify the jinja templates exists or not.
+ c. schedule the cron job for the python script e.g */15 * * * * cd /home/ubuntu/Nexus9k_Sailaja/nexus9000/nexusscripts && python interface_monitor.py
+
+
+
+2. Sytem-Level Resources monitoring
+
+ Steps :
+
+ a. Configuration file is reused from the interface monitoring (check the host details and email address)
+ b. verify the jinja templates exists or not.
+ c. schedule the cron job for the python script e.g */15 * * * * cd /home/ubuntu/Nexus9k_Sailaja/nexus9000/nexusscripts && python systemresc_monitor.py
diff --git a/nexusscripts/off-box/monitoring/html/interface_10.1.150.12_.html b/nexusscripts/off-box/monitoring/html/interface_10.1.150.12_.html
new file mode 100644
index 00000000..276a9b9f
--- /dev/null
+++ b/nexusscripts/off-box/monitoring/html/interface_10.1.150.12_.html
@@ -0,0 +1,4264 @@
+
+
+
+
+
+ Nexus Switch Interface monitoring
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : Nexus9000 C9396PX Chassis
+
OS Version : 6.1(2)I3(1)
+
+
+
+
+
+
Interface | In_Error | Out_Error |
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/monitoring/html/systemresc_10.1.150.12_.html b/nexusscripts/off-box/monitoring/html/systemresc_10.1.150.12_.html
new file mode 100644
index 00000000..b9d0653b
--- /dev/null
+++ b/nexusscripts/off-box/monitoring/html/systemresc_10.1.150.12_.html
@@ -0,0 +1,113 @@
+
+
+
+
+
+ Nexus Switch System monitoring
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : Nexus9000 C9396PX Chassis
+
OS Version : 6.1(2)I3(1)
+
+
+
+
+
+
+
CPU Utilization( % ) |
Parameters | Overview |
+
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
Memory Usage( Bytes ) |
Parameters | Overview |
+
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+ |
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/monitoring/interface_monitor.py b/nexusscripts/off-box/monitoring/interface_monitor.py
new file mode 100644
index 00000000..02ce5f78
--- /dev/null
+++ b/nexusscripts/off-box/monitoring/interface_monitor.py
@@ -0,0 +1,301 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Monitoring
+:Box Type:Off-Box
+:Title:Interface Monitoring
+:Short Description:This script is to monitor Interface counters.
+:Long Description:This script is to monitor Interface counters like
+Errors etc.
+:Input:command to check the interface status
+ e.g show interface ethernet 1/1
+:Output:parse the json output and update the html file
+"""
+
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+
+from collections import OrderedDict
+import os
+import requests
+import json
+import ConfigParser
+import datetime
+import sys
+import re
+
+from jinja2 import Template
+from jinja2 import Environment, FileSystemLoader
+
+PATH = os.getcwd()
+TEMPLATE_ENVIRONMENT = Environment(
+ autoescape=False,
+ loader=FileSystemLoader(os.path.join(PATH, 'templates')),
+ trim_blocks=False)
+
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nexus_automation.cfg')
+
+#switch host details
+ipaddress = config.get('HostDetails', 'ipaddress')
+username = config.get('HostDetails', 'username')
+password = config.get('HostDetails', 'password')
+
+#list of to addresses for the email
+to_addresses = config.get('EmailDetails', 'to_addresses')
+
+#get the current working directory
+directory = os.getcwd()
+#html file location
+out_template = 'monitor_interface.jinja'
+out_html = directory+'/html/interface_'+ipaddress+'_.html'
+
+
+#remove the existing html file
+if (os.path.exists(out_html)):
+ os.remove(out_html)
+
+#check the configuration details
+if (ipaddress == ''):
+ print "Please update the configuration file with Switch IPAddress"
+ exit(1)
+
+if ((username and password) == ''):
+ print "Please update the configuration file with Switch User Credentials"
+ exit(1)
+elif (username == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+elif (password == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+
+
+
+
+"""
+class to monitor the interface counters
+like errors etc
+
+"""
+
+class Interface_Monit:
+
+ myheaders = {'content-type':'application/json-rpc'}
+
+ url = "http://"+ipaddress+"/ins"
+
+
+ in_err = {}; out_err = {}; interface_list = []; rx_tx_dict = {};
+
+ def render_template(self, template_filename, context):
+ return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
+
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+ global chassis_id, sys_version
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show version","version":1},"id":1},]
+ response = requests.post(Interface_Monit.url,data=json.dumps(payload),headers=Interface_Monit.myheaders,auth=(username,password)).json()
+ chassis_id = response['result']['body']['chassis_id']
+ sys_version = response['result']['body']['rr_sys_ver']
+
+
+
+ """
+ Input: command to check the interface status
+ e.g show interface ethernet 1/1
+ Output : parse the json output and update the html file
+ """
+ def monit(self, cmd, i, j):
+
+ interfaceob = Interface_Monit()
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":cmd,"version":1},"id":1},]
+
+ response = requests.post(Interface_Monit.url,data=json.dumps(payload),headers=Interface_Monit.myheaders,auth=(username,password)).json()
+
+
+ in_err = int(response['result']['body']['TABLE_interface']['ROW_interface']['eth_inerr'])
+ out_err = int(response['result']['body']['TABLE_interface']['ROW_interface']['eth_outerr'])
+ key = str(i)+"/"+str(j)
+
+
+ if ((in_err) == 0):
+ Interface_Monit.in_err.update({key:"No"})
+ else:
+ Interface_Monit.in_err.update({key:"Yes"})
+ if ((out_err) == 0):
+ Interface_Monit.out_err.update({key:"No"})
+ else:
+ Interface_Monit.in_err.update({key:"Yes"})
+
+
+
+
+ def interface_rx_tx(self):
+ table = "{0:16}{1:9}{2:9}{3:9}{4:9}{5:9}{6:9}{7:9}{8:9}"
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show interface status","version":1},"id":1},]
+ response = requests.post(Interface_Monit.url,data=json.dumps(payload),headers=Interface_Monit.myheaders,auth=(username,password)).json()
+
+ Interface_Monit.interface_list = response['result']['body']['TABLE_interface']['ROW_interface']
+ print '----------------------------------------------------------------------------------------------------------'
+ print table.format("Interface", "Rx Mbps", "Rx %", "Rx pps", "Tx Mbps", "Tx %", "Tx pps", "In Error", "Out Error")
+ print '----------------------------------------------------------------------------------------------------------'
+
+ counter = 0;
+ for i in Interface_Monit.interface_list:
+ for key,value in i.items():
+ counter = counter+1;
+ if (key == 'interface'):
+ m = re.search('Ethernet(.*)', value)
+ if m:
+ found = m.group(1)
+ slotport = found.split('/')
+
+ cmd = "show interface ethernet"+str(slotport[0])+"/"+str(slotport[1])
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":cmd,"version":1},"id":1},]
+
+ response = requests.post(Interface_Monit.url,data=json.dumps(payload),headers=Interface_Monit.myheaders,auth=(username,password)).json()
+
+ bw = int(response['result']['body']['TABLE_interface']['ROW_interface']['eth_bw'])
+ rx_bps = int(response['result']['body']['TABLE_interface']['ROW_interface']['eth_inrate1_bits'])
+ rx_mbps = round((rx_bps / 1000000), 1)
+ rx_pcnt = round((rx_bps / 1000) * 100 / bw, 1)
+ rx_pps = response['result']['body']['TABLE_interface']['ROW_interface']['eth_inrate1_pkts']
+
+ tx_bps = int(response['result']['body']['TABLE_interface']['ROW_interface']['eth_outrate1_bits'])
+ tx_mbps = round((tx_bps / 1000000), 1)
+ tx_pcnt = round((tx_bps / 1000) * 100 / bw, 1)
+ tx_pps = response['result']['body']['TABLE_interface']['ROW_interface']['eth_outrate1_pkts']
+
+ in_err = int(response['result']['body']['TABLE_interface']['ROW_interface']['eth_inerr'])
+ out_err = int(response['result']['body']['TABLE_interface']['ROW_interface']['eth_outerr'])
+
+
+ print table.format(value, str(rx_mbps), str(rx_pcnt) + '%', rx_pps, str(tx_mbps), str(tx_pcnt) + '%', tx_pps, in_err, out_err)
+ sys.stdout.flush()
+ Interface_Monit.rx_tx_dict.update({value:{'counter':counter, 'rx_mbps':rx_mbps, 'rx_pcnt':rx_pcnt, 'rx_pps':rx_pps, 'tx_mbps':tx_mbps, 'tx_pcnt':tx_pcnt, 'tx_pps':tx_pps, 'in_err':in_err, 'out_err':out_err}})
+
+
+
+
+
+ #create a command to get the interface status
+ def interface_err(self):
+ interfaceob = Interface_Monit()
+ for i in Interface_Monit.interface_list:
+ for key,value in i.items():
+ if (key == 'interface'):
+ m = re.search('Ethernet(.*)', value)
+ if m:
+ found = m.group(1)
+ slotport = found.split('/')
+
+ cmd = "show interface ethernet"+str(slotport[0])+"/"+str(slotport[1])
+ interfaceob.monit(cmd, slotport[0], slotport[1])
+
+
+ def status(self):
+ global input_counter, output_counter, inerr_interface, outerr_interface
+ input_counter = 0; output_counter=0; inerr_interface = []; outerr_interface = [];
+
+ for key,value in Interface_Monit.in_err.items():
+ if (value == "Yes"):
+ input_counter = input_counter + 1;
+ inerr_interface.append(key)
+
+ for key,value in Interface_Monit.out_err.items():
+ if (value == "Yes"):
+ output_counter = output_counter + 1;
+ outerr_interface.append(key)
+
+
+ if (input_counter == 0):
+ print "Number of Interfaces with Input Errors is : " + ' ' + str(input_counter)
+ else:
+ print "Number of Interfaces with Input Errors is : " + ' ' + str(input_counter)
+ for key in inerr_interface:
+ print key
+
+ if (output_counter == 0):
+ print "Number of Interfaces with Output Errors is : " + ' ' + str(output_counter)
+ else:
+ print "Number of Interfaces with Output Errors is : " + ' ' + str(output_counter)
+ for key in outerr_interface:
+ print key
+
+
+ def updatetemp(self):
+ interfaceob = Interface_Monit()
+
+ Interface_Monit.rx_tx_dict = OrderedDict(sorted(Interface_Monit.rx_tx_dict.items(), key= lambda x: x[1]['counter']))
+
+
+ templateVars = { "title" : "Nexus Switch Interface monitoring",
+ "description" : "Interface monitoring",
+ "chassis_id" : chassis_id,
+ "os_version" : sys_version,
+ "in_err" : Interface_Monit.in_err,
+ "out_err" : Interface_Monit.out_err,
+ "input_counter" : input_counter,
+ "output_counter" : output_counter,
+ "inerr_interface" : inerr_interface,
+ "outerr_interface" : outerr_interface,
+ "rx_tx_dict" : Interface_Monit.rx_tx_dict
+
+
+ }
+ with open(out_html, 'a') as f:
+ outputText = interfaceob.render_template(out_template, templateVars)
+ f.write(outputText)
+
+ def send_mail(self):
+
+ #account setup
+ username = 'nexus9000.adm@gmail.com';
+ password = '!cisco123';
+ server = 'smtp.gmail.com:587';
+ timestamp = datetime.datetime.now()
+
+ msg = MIMEMultipart()
+ msg['From'] = username
+ msg['To'] = to_addresses
+ msg['Subject'] = 'Nexus 9000 Interface Monitoring Email' + ' ' + 'on' + ' ' + timestamp.strftime("%d/%m/%Y") + '@' + timestamp.strftime("%H:%M:%S")
+
+ fp = open(out_html, 'rb')
+ content = fp.read()
+ part = MIMEText(content, 'html')
+
+ msg.attach(part)
+
+ try:
+ mailserver = smtplib.SMTP(server)
+ # identify ourselves to smtp gmail client
+ mailserver.ehlo()
+ # secure our email with tls encryption
+ mailserver.starttls()
+ # re-identify ourselves as an encrypted connection
+ mailserver.ehlo()
+ mailserver.login(username, password)
+
+ mailserver.sendmail(msg['From'],(msg['To'].split(',')),msg.as_string())
+
+ mailserver.quit()
+ print "Successfully sent email"
+
+ except Exception:
+ print "Error: unable to send email"
+
+
+
+
+if __name__ == '__main__':
+ interfaceobj = Interface_Monit()
+ interfaceobj.nexus_version()
+ interfaceobj.interface_rx_tx()
+ interfaceobj.interface_err()
+ interfaceobj.status()
+ interfaceobj.updatetemp()
+ interfaceobj.send_mail()
diff --git a/nexusscripts/off-box/monitoring/nexus_automation.cfg b/nexusscripts/off-box/monitoring/nexus_automation.cfg
new file mode 100644
index 00000000..d31d8e52
--- /dev/null
+++ b/nexusscripts/off-box/monitoring/nexus_automation.cfg
@@ -0,0 +1,10 @@
+[HostDetails]
+#Nexus Switch ipaddress and user details
+ipaddress=
+username=
+password=
+
+[EmailDetails]
+#email to address list e.g sailajap@onecloudinc.com,darshan@onecloudinc.com
+to_addresses=
+
diff --git a/nexusscripts/off-box/monitoring/systemresc_monitor.py b/nexusscripts/off-box/monitoring/systemresc_monitor.py
new file mode 100644
index 00000000..19af2511
--- /dev/null
+++ b/nexusscripts/off-box/monitoring/systemresc_monitor.py
@@ -0,0 +1,207 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Monitoring
+:Box Type:Off-Box
+:Title:System Resources Monitoring
+:Short Description:This script is to monitor system-level resources.
+:Long Description:This script is to monitor system-level resources
+like cpu utilization, memory usage etc
+:Input:command to check the system resources status
+ e.g show system resources
+:Output:parse the json output and update the html file
+"""
+
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+import os
+import requests
+import json
+import ConfigParser
+import datetime
+import math
+
+from jinja2 import Template
+from jinja2 import Environment, FileSystemLoader
+
+PATH = os.getcwd()
+TEMPLATE_ENVIRONMENT = Environment(
+ autoescape=False,
+ loader=FileSystemLoader(os.path.join(PATH, 'templates')),
+ trim_blocks=False)
+
+
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nexus_automation.cfg')
+
+ipaddress = config.get('HostDetails', 'ipaddress')
+username = config.get('HostDetails', 'username')
+password = config.get('HostDetails', 'password')
+
+#list of to addresses for the email
+to_addresses = config.get('EmailDetails', 'to_addresses')
+
+#get the current working directory
+directory = os.getcwd()
+#html file and template location
+out_template = 'monitor_systemresc.jinja'
+out_html = directory+'/html/systemresc_'+ipaddress+'_.html'
+
+#remove the existing html file
+if (os.path.exists(out_html)):
+ os.remove(out_html)
+
+#check the configuration details
+if (ipaddress == ''):
+ print "Please update the configuration file with Switch IPAddress"
+ exit(1)
+
+if ((username and password) == ''):
+ print "Please update the configuration file with Switch User Credentials"
+ exit(1)
+elif (username == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+elif (password == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+
+
+"""
+class to monitor system-level resources
+cpu-utilization, memory usage
+
+"""
+
+class System_Monit:
+
+ myheaders = {'content-type':'application/json-rpc'}
+
+ url = "http://"+ipaddress+"/ins"
+
+ cpu_utilization = {}
+ mem_usage = {}
+
+ def render_template(self, template_filename, context):
+ return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
+
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+
+ global chassis_id, sys_version
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show version","version":1},"id":1},]
+ response = requests.post(System_Monit.url,data=json.dumps(payload),headers=System_Monit.myheaders,auth=(username,password)).json()
+ chassis_id = response['result']['body']['chassis_id']
+ sys_version = response['result']['body']['rr_sys_ver']
+
+ #get the monitoring data from the nexus switch
+ def monit_data(self):
+
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show system resources","version":1},"id":1},]
+ response = requests.post(System_Monit.url,data=json.dumps(payload),headers=System_Monit.myheaders,auth=(username,password)).json()
+ self.cpu_kernel = response['result']['body']['cpu_state_kernel']
+ self.cpu_idle = response['result']['body']['cpu_state_idle']
+ self.cpu_user = response['result']['body']['cpu_state_user']
+
+ #update the cpu_utilization dictionary
+ System_Monit.cpu_utilization.update({'Cpu_state_kernel':self.cpu_kernel})
+ System_Monit.cpu_utilization.update({'Cpu_state_idle':self.cpu_idle})
+ System_Monit.cpu_utilization.update({'Cpu_state_user':self.cpu_user})
+
+
+ self.mem_used = response['result']['body']['memory_usage_used']
+ self.mem_free = response['result']['body']['memory_usage_free']
+ self.mem_total = response['result']['body']['memory_usage_total']
+ self.mem_status = response['result']['body']['current_memory_status']
+
+ #update the memory usage dictionary
+ System_Monit.mem_usage.update({'Memory_Usage_Used':self.mem_used})
+ System_Monit.mem_usage.update({'Memory_Usage_Free':self.mem_free})
+ System_Monit.mem_usage.update({'Memory_Usage_Total':self.mem_total})
+ System_Monit.mem_usage.update({'Current_Memory_Status':self.mem_status})
+
+ #overall cpu utilization and memory usage in percentage
+ def status(self):
+ global cpu_percent,mem_percent
+ total_cpu = float(System_Monit.cpu_utilization['Cpu_state_kernel']) + float(System_Monit.cpu_utilization['Cpu_state_user'])
+ cpu_percent = (total_cpu)/2
+ print "Overall CPU Utilization is : " + str(cpu_percent) + "%"
+
+
+ mem_used = float(System_Monit.mem_usage['Memory_Usage_Used']) / float(System_Monit.mem_usage['Memory_Usage_Total'])
+
+ memory_per = mem_used*100
+ mem_percent = round(memory_per,2)
+
+ print "Overall Memory Usage is : " + str(mem_percent) + "%" + ' '+ "(" + str(System_Monit.mem_usage['Memory_Usage_Used']) + \
+ ' ' + "Used in Bytes" + "/" + ' ' + str(System_Monit.mem_usage['Memory_Usage_Free']) + ' ' + "Free in Bytes" + ")"
+
+
+ def updatetemp(self):
+ systemob = System_Monit()
+ templateVars = { "title" : "Nexus Switch System monitoring",
+ "description" : "System-Level resources monitoring",
+ "chassis_id" : chassis_id,
+ "os_version" : sys_version,
+ "cpu_percent" : cpu_percent,
+ "mem_percent" : mem_percent,
+ "cpu_util" : System_Monit.cpu_utilization,
+ "mem_usage" : System_Monit.mem_usage
+ }
+ with open(out_html, 'a') as f:
+ outputText = systemob.render_template(out_template, templateVars)
+ f.write(outputText)
+
+
+ def send_mail(self):
+
+ #account setup
+ username = 'nexus9000.adm@gmail.com';
+ password = '!cisco123';
+ server = 'smtp.gmail.com:587';
+ timestamp = datetime.datetime.now()
+
+ msg = MIMEMultipart()
+ msg['From'] = username
+ msg['To'] = to_addresses
+ msg['Subject'] = 'Nexus 9000 System-Level Resources Monitoring Email' + ' ' + 'on' + ' ' + timestamp.strftime("%d/%m/%Y") + '@' + timestamp.strftime("%H:%M:%S")
+
+ fp = open(out_html, 'rb')
+ content = fp.read()
+ part = MIMEText(content, 'html')
+
+ msg.attach(part)
+
+ try:
+ mailserver = smtplib.SMTP(server)
+ # identify ourselves to smtp gmail client
+ mailserver.ehlo()
+ # secure our email with tls encryption
+ mailserver.starttls()
+ # re-identify ourselves as an encrypted connection
+ mailserver.ehlo()
+ mailserver.login(username, password)
+
+ mailserver.sendmail(msg['From'],(msg['To'].split(',')),msg.as_string())
+
+ mailserver.quit()
+ print "Successfully sent email"
+
+ except Exception:
+ print "Error: unable to send email"
+
+
+
+
+
+
+if __name__ == '__main__':
+ systemob = System_Monit()
+ systemob.nexus_version()
+ systemob.monit_data()
+ systemob.status()
+ systemob.updatetemp()
+ systemob.send_mail()
diff --git a/nexusscripts/off-box/monitoring/templates/monitor_interface.jinja b/nexusscripts/off-box/monitoring/templates/monitor_interface.jinja
new file mode 100644
index 00000000..fb09b870
--- /dev/null
+++ b/nexusscripts/off-box/monitoring/templates/monitor_interface.jinja
@@ -0,0 +1,73 @@
+
+
+
+
+
+ {{ title }}
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : {{ chassis_id }}
+
OS Version : {{ os_version }}
+
+
+
+
+
+{% if input_counter == 0 %}
+
+{% else %}
+
+{% for i in inerr_interface %}
+
+
+{% endfor %}
+{% endif %}
+
+{% if output_counter == 0 %}
+
+{% else %}
+
+{% for j in outerr_interface %}
+
+
+{% endfor %}
+{% endif %}
+
+
+
+
+
+
Interface Monitoring (Drops, Utilization, Errors) |
Interface | Rx Mbps | Rx % | Rx pps | Tx Mbps | Tx % | Tx pps | In Error | Out Error |
+
+
+{% for key,value in rx_tx_dict.items() %}
+
+ |
+{% for k,v in value.items() %}
+{% if k == 'counter' %}
+{% set testvar = 'it worked' %}
+{% else %}
+ |
+{% endif %}
+{% endfor %}
+
+
+{% endfor %}
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/monitoring/templates/monitor_systemresc.jinja b/nexusscripts/off-box/monitoring/templates/monitor_systemresc.jinja
new file mode 100644
index 00000000..0fc26aa5
--- /dev/null
+++ b/nexusscripts/off-box/monitoring/templates/monitor_systemresc.jinja
@@ -0,0 +1,81 @@
+
+
+
+
+
+ {{ title }}
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : {{ chassis_id }}
+
OS Version : {{ os_version }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
CPU Utilization( % ) |
Parameters | Overview |
+
+
+{% for key,value in cpu_util.items() %}
+
+
+
+ |
+
+
+ |
+
+{%endfor %}
+
+
+
+
+
+
+
+
+
+
+
Memory Usage( Bytes ) |
Parameters | Overview |
+
+
+{% for key,value in mem_usage.items() %}
+
+
+
+ |
+
+
+ |
+
+{%endfor %}
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/troubleshoot/fex_troubleshoot.py b/nexusscripts/off-box/troubleshoot/fex_troubleshoot.py
new file mode 100644
index 00000000..49415b9d
--- /dev/null
+++ b/nexusscripts/off-box/troubleshoot/fex_troubleshoot.py
@@ -0,0 +1,205 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Troubleshooting
+:Box Type:Off-Box
+:Title:FEX issues
+:Short Description:To identify FEX issues
+:Long Description:Check the FEX state
+installed/enabled etc
+:Input:command to check the FEX installation,
+associated interfaces etc
+:Output:FEX status
+"""
+
+import smtplib
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+import os
+import requests
+import json
+import ConfigParser
+import datetime
+
+from jinja2 import Template
+from jinja2 import Environment, FileSystemLoader
+
+PATH = os.getcwd()
+TEMPLATE_ENVIRONMENT = Environment(
+ autoescape=False,
+ loader=FileSystemLoader(os.path.join(PATH, 'templates')),
+ trim_blocks=False)
+
+
+
+#read the nexus configuration file
+config=ConfigParser.ConfigParser()
+config.read('nexus_automation.cfg')
+
+ipaddress = config.get('HostDetails', 'ipaddress')
+username = config.get('HostDetails', 'username')
+password = config.get('HostDetails', 'password')
+
+#list of to addresses for the email
+to_addresses = config.get('EmailDetails', 'to_addresses')
+
+#get the current working directory
+directory = os.getcwd()
+#html file and template location
+out_template = 'troubleshoot_fex.jinja'
+out_html = directory+'/html/fex_'+ipaddress+'_.html'
+
+#remove the existing html file
+if (os.path.exists(out_html)):
+ os.remove(out_html)
+
+#check the configuration details
+if (ipaddress == ''):
+ print "Please update the configuration file with Switch IPAddress"
+ exit(1)
+
+if ((username and password) == ''):
+ print "Please update the configuration file with Switch User Credentials"
+ exit(1)
+elif (username == ''):
+ print "Please update the configuration file with Switch User Creentials "
+ exit(1)
+elif (password == ''):
+ print "Please update the configuration file with Switch User Credentials "
+ exit(1)
+
+
+
+"""
+
+Class to troubleshoot FEX on the Nexus Switch
+"""
+
+class FEX_Troubleshoot:
+
+ stat = '';
+ interface_stat = '';
+ interface_list = [];
+ myheaders = {'content-type':'application/json-rpc'}
+
+ url = "http://"+ipaddress+"/ins"
+
+ def render_template(self, template_filename, context):
+ return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
+
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+
+ global chassis_id, sys_version
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show version","version":1},"id":1},]
+ response = requests.post(FEX_Troubleshoot.url,data=json.dumps(payload),headers=FEX_Troubleshoot.myheaders,auth=(username,password)).json()
+ chassis_id = response['result']['body']['chassis_id']
+ sys_version = response['result']['body']['rr_sys_ver']
+
+ def fex_status(self):
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show feature-set fex","version":1},"id":1},]
+ response = requests.post(FEX_Troubleshoot.url,data=json.dumps(payload),headers=FEX_Troubleshoot.myheaders,auth=(username,password)).json()
+ status = response['result']['body']['TABLE-cfcFeatureSetTable']['cfcFeatureSetOpStatus']
+ FEX_Troubleshoot.stat = " FEX is " + status
+ print FEX_Troubleshoot.stat
+
+ def fex_interfaces(self):
+ try:
+ payload = [{"jsonrpc":"2.0","method":"cli","params":{"cmd":"show interface fex-fabric","version":1},"id":1},]
+ response = requests.post(FEX_Troubleshoot.url,data=json.dumps(payload),headers=FEX_Troubleshoot.myheaders,auth=(username,password)).json()
+
+ status = response['result']['body']['TABLE_fex_fabric']['ROW_fex_fabric']
+ FEX_Troubleshoot.stat = " Interfaces have detected a Fabric Extender uplink"
+ print FEX_Troubleshoot.stat
+
+ if (isinstance(status, list)):
+ for i in status:
+ for key,value in i.items():
+ if (key == 'fbr_port'):
+ print value
+ FEX_Troubleshoot.interface_list.append(value)
+ elif (isinstance(status, dict)):
+ for key,value in status.items():
+ if (key == 'fbr_port'):
+ print value
+ FEX_Troubleshoot.interface_list.append(value)
+ else:
+ print "Not implemented for this response type"
+
+
+
+ except:
+ FEX_Troubleshoot.stat = "Interfaces are not configured to FEX uplink"
+ print FEX_Troubleshoot.interface_stat
+
+
+
+
+
+
+ #update the jinja template with the data
+ def updatetemp(self):
+ systemob = FEX_Troubleshoot()
+ templateVars = { "title" : "Nexus Switch Configuration management",
+ "description" : "FEX Configuration",
+ "chassis_id" : chassis_id,
+ "os_version" : sys_version,
+ "status" : FEX_Troubleshoot.stat,
+ "interface_stat" : FEX_Troubleshoot.interface_stat,
+ "interface_list" : FEX_Troubleshoot.interface_list
+ }
+ with open(out_html, 'a') as f:
+ outputText = systemob.render_template(out_template, templateVars)
+ f.write(outputText)
+
+
+ def send_mail(self):
+
+ #account setup
+ username = 'nexus9000.adm@gmail.com';
+ password = '!cisco123';
+ server = 'smtp.gmail.com:587';
+ timestamp = datetime.datetime.now()
+
+ msg = MIMEMultipart()
+ msg['From'] = username
+ msg['To'] = to_addresses
+ msg['Subject'] = 'Nexus 9000 FEX Configuration Email' + ' ' + 'on' + ' ' + timestamp.strftime("%d/%m/%Y") + '@' + timestamp.strftime("%H:%M:%S")
+
+ fp = open(out_html, 'rb')
+ content = fp.read()
+ part = MIMEText(content, 'html')
+
+ msg.attach(part)
+
+ try:
+ mailserver = smtplib.SMTP(server)
+ # identify ourselves to smtp gmail client
+ mailserver.ehlo()
+ # secure our email with tls encryption
+ mailserver.starttls()
+ # re-identify ourselves as an encrypted connection
+ mailserver.ehlo()
+ mailserver.login(username, password)
+
+ mailserver.sendmail(msg['From'],(msg['To'].split(',')),msg.as_string())
+
+ mailserver.quit()
+ print "Successfully sent email"
+
+ except Exception:
+ print "Error: unable to send email"
+
+
+
+
+
+
+if __name__ == '__main__':
+ systemob = FEX_Troubleshoot()
+ systemob.nexus_version()
+ systemob.fex_status()
+ systemob.fex_interfaces()
+ systemob.updatetemp()
+ systemob.send_mail()
+
diff --git a/nexusscripts/off-box/troubleshoot/html/fex_10.1.150.12_.html b/nexusscripts/off-box/troubleshoot/html/fex_10.1.150.12_.html
new file mode 100644
index 00000000..a78717a0
--- /dev/null
+++ b/nexusscripts/off-box/troubleshoot/html/fex_10.1.150.12_.html
@@ -0,0 +1,38 @@
+
+
+
+
+
+ Nexus Switch Configuration management
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : Nexus9000 C9396PX Chassis
+
OS Version : 6.1(2)I3(1)
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/troubleshoot/html/systemresc_10.1.150.12_.html b/nexusscripts/off-box/troubleshoot/html/systemresc_10.1.150.12_.html
new file mode 100644
index 00000000..e69de29b
diff --git a/nexusscripts/off-box/troubleshoot/nexus_automation.cfg b/nexusscripts/off-box/troubleshoot/nexus_automation.cfg
new file mode 100644
index 00000000..be9c5dfd
--- /dev/null
+++ b/nexusscripts/off-box/troubleshoot/nexus_automation.cfg
@@ -0,0 +1,11 @@
+[HostDetails]
+#Nexus Switch ipaddress and user details
+ipaddress=10.1.150.12
+username=admin
+password=!cisco123
+
+
+[EmailDetails]
+#email to address list
+to_addresses=sailajap@onecloudinc.com,
+
diff --git a/nexusscripts/off-box/troubleshoot/templates/troubleshoot_fex.jinja b/nexusscripts/off-box/troubleshoot/templates/troubleshoot_fex.jinja
new file mode 100644
index 00000000..a14cee1f
--- /dev/null
+++ b/nexusscripts/off-box/troubleshoot/templates/troubleshoot_fex.jinja
@@ -0,0 +1,62 @@
+
+
+
+
+
+ {{ title }}
+
+
+
+
+
+
+
+
+
Nexus Switch Chassis id : {{ chassis_id }}
+
OS Version : {{ os_version }}
+
+
+
+
+
+
+
FEX Status |
+
+
+{% if status %}
+
+
+
+{%endif %}
+{%if interface_stat %}
+
+
+
+{%endif %}
+
+
+
+
+
+
+
+
+{%if interface_list %}
+
+{% for j in interface_list %}
+
+
+{% endfor %}
+{%endif %}
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/nexusscripts/off-box/upgrade_patch_mgmt/patch_mgmt.py b/nexusscripts/off-box/upgrade_patch_mgmt/patch_mgmt.py
new file mode 100644
index 00000000..baf99dcd
--- /dev/null
+++ b/nexusscripts/off-box/upgrade_patch_mgmt/patch_mgmt.py
@@ -0,0 +1,376 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:OS-Mgmt
+:Box Type:Off-Box
+:Title:Patch Management
+:Short Description:This script is to perform patch related operations
+:Long Description:This script is to perform operations like
+ copy, activate, deactivate, remove patch files.
+:Input:N9K Address, username, password, tftp_address, smu_file, action
+:Output:status/result of the patch management action
+"""
+
+"""Examples
+
+(1) install activate
+(2) install commit (active)
+(3) install deactivate
+(4) install commit (inactive)
+(5) install remove
+
+(1) install activate
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action activate
+install add bootflash:n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 179 completed successfully at Tue Jan 27 09:13:02 2015
+show install inactive
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+install activate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 180 completed successfully at Tue Jan 27 09:13:08 2015
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Tue Jan 27 09:13:08 2015
+Install operation 180 by user admin at Tue Jan 27 09:13:02 2015
+Install activate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 180 completed successfully at Tue Jan 27 09:13:08 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Committed Packages:
+Tue Jan 27 09:13:39 2015
+Install operation 180 by user admin at Tue Jan 27 09:13:02 2015
+Install activate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 180 completed successfully at Tue Jan 27 09:13:08 2015
+
+(2) install commit (active)
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --use r admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action commit_active
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 181 completed successfully at Tue Jan 27 09:14:09 2015
+Tue Jan 27 09:14:09 2015
+Install operation 181 by user admin at Tue Jan 27 09:14:07 2015
+Install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 181 completed successfully at Tue Jan 27 09:14:09 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --use r admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Committed Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Tue Jan 27 09:14:17 2015
+Install operation 181 by user admin at Tue Jan 27 09:14:07 2015
+Install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 181 completed successfully at Tue Jan 27 09:14:09 2015
+
+(3) install deactivate
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action deactivate
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+install deactivate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 182 completed successfully at Tue Jan 27 09:15:10 2015
+show install inactive
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Tue Jan 27 09:15:10 2015
+Install operation 182 by user admin at Tue Jan 27 09:15:04 2015
+Install deactivate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 182 completed successfully at Tue Jan 27 09:15:10 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Active Packages:
+Committed Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Tue Jan 27 09:15:18 2015
+Install operation 182 by user admin at Tue Jan 27 09:15:04 2015
+Install deactivate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 182 completed successfully at Tue Jan 27 09:15:10 2015
+
+(4) install commit (inactive)
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action commit_inactive
+show install inactive
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 184 completed successfully at Tue Jan 27 09:16:03 2015
+Tue Jan 27 09:16:03 2015
+Install operation 184 by user admin at Tue Jan 27 09:16:01 2015
+Install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 184 completed successfully at Tue Jan 27 09:16:03 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Active Packages:
+Committed Packages:
+Tue Jan 27 09:16:10 2015
+Install operation 184 by user admin at Tue Jan 27 09:16:01 2015
+Install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 184 completed successfully at Tue Jan 27 09:16:03 2015
+
+(5) install remove
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action remove
+show install inactive
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 185 completed successfully at Tue Jan 27 09:16:46 2015
+Tue Jan 27 09:16:46 2015
+Install operation 185 by user admin at Tue Jan 27 09:16:46 2015
+Install remove n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 185 completed successfully at Tue Jan 27 09:16:46 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+Active Packages:
+Committed Packages:
+Tue Jan 27 09:16:50 2015
+Install operation 185 by user admin at Tue Jan 27 09:16:46 2015
+Install remove n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 185 completed successfully at Tue Jan 27 09:16:46 2015
+
+End of Examples
+"""
+
+
+import argparse
+import getpass
+import sys
+
+sys.path.append("../../../nx-os/nxapi/utils")
+
+from nxapi_utils import NXAPI
+import xmltodict
+
+
+class Args(object):
+ def __init__(self, args):
+ self.n9k = args.hostname
+ self.username = args.username
+ self.password = args.password
+ if not self.password:
+ self.password = getpass.getpass()
+ self.tftp_address = args.tftp_address
+ self.smu_filename = args.smu_filename
+ self.action = args.action
+
+
+def initialize_nxapi_handler(params):
+ nxapi = NXAPI()
+ nxapi.set_target_url('http://' + params.n9k + '/ins')
+ nxapi.set_username(params.username)
+ nxapi.set_password(params.password)
+ nxapi.set_msg_type('cli_conf')
+ return nxapi
+
+
+def check_status(dict_res):
+ if dict_res['ins_api']['outputs']['output']['code'] == '200' and \
+ dict_res['ins_api']['outputs']['output']['msg'] == 'Success':
+ print dict_res['ins_api']['outputs']['output']['body']
+ return True
+ else:
+ print 'Error Msg:' + dict_res['ins_api']['outputs']['output']['msg']
+ print 'Code:' + dict_res['ins_api']['outputs']['output']['code']
+ return False
+
+
+def copy_patch_file(params, nxapi_handler):
+ print 'copy tftp://'+ params.tftp_address + '/' + params.smu_filename +\
+ ' bootflash:// vrf management'
+ nxapi_handler.set_cmd('copy tftp://'+ params.tftp_address + '/' +
+ params.smu_filename + ' bootflash:// vrf management')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def list_patch_file(params, nxapi_handler):
+ print 'dir bootflash:' + params.smu_filename
+ nxapi_handler.set_cmd('dir bootflash:' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def add_module(params, nxapi_handler):
+ print 'install add bootflash:' + params.smu_filename
+ nxapi_handler.set_cmd('install add bootflash:' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def list_inactive_modules(nxapi_handler):
+ print 'show install inactive'
+ nxapi_handler.set_cmd('show install inactive')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def activate_patch_file(params, nxapi_handler):
+ print 'install activate ' + params.smu_filename
+ nxapi_handler.set_cmd('install activate ' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+def commit_active_patch_file(params, nxapi_handler):
+ print 'install commit ' + params.smu_filename
+ nxapi_handler.set_cmd('install commit ' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+def commit_inactive_patch_file(params, nxapi_handler):
+ print 'install commit ' + params.smu_filename
+ nxapi_handler.set_cmd('install commit ' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+def list_modules_status(nxapi_handler):
+# print 'show install inactive'
+ nxapi_handler.set_cmd('show install inactive')
+ returnData = nxapi_handler.send_req()
+ dict_res_inactive = xmltodict.parse(returnData[1])
+
+# print 'show install active'
+ nxapi_handler.set_cmd('show install active')
+ returnData = nxapi_handler.send_req()
+ dict_res_active = xmltodict.parse(returnData[1])
+
+# print 'show install committed'
+ nxapi_handler.set_cmd('show install committed')
+ returnData = nxapi_handler.send_req()
+ dict_res_committed = xmltodict.parse(returnData[1])
+ return check_status(dict_res_inactive), check_status(dict_res_active), check_status(dict_res_committed)
+
+def list_active_modules(nxapi_handler):
+ nxapi_handler.set_cmd('show install active')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def deactivate_patch_file(params, nxapi_handler):
+ print 'install deactivate ' + params.smu_filename
+ nxapi_handler.set_cmd('install deactivate ' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def remove_modules(params, nxapi_handler):
+ nxapi_handler.set_cmd('install remove ' + params.smu_filename + ' forced')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def show_install_log(nxapi_handler):
+ nxapi_handler.set_cmd('show install log last')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 OS software patch management utility.',
+ epilog="""to openstack cluster.""")
+
+ parser.add_argument('--n9k', '-i', dest='hostname',
+ help='Nexus 9XXX hostname or ip address', required=True)
+ parser.add_argument('--user', '-u', dest='username',
+ help='Username to login to Nexus 9XXX switch', required=True)
+ parser.add_argument('--password', '-p', dest='password',
+ help='Password to login to Nexus 9XXX switch')
+ parser.add_argument('--tftp_address', '-a', dest='tftp_address',
+ help='Tftp server ip-address.')
+ parser.add_argument('--smu_filename', '-f', dest='smu_filename',
+ help='SMU filename.', required=True)
+ parser.add_argument('--action', '-o', dest='action',
+ help='Action Install/Remove patch file.', required=True,
+ choices = ['copy', 'activate', 'deactivate', 'commit_active', 'commit_inactive', 'remove', 'status'])
+ args = parser.parse_args()
+ return Args(args)
+
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+
+ nxapi_handler = initialize_nxapi_handler(params)
+
+ if params.action == 'copy':
+ if not params.tftp_address:
+ params.tftp_address = raw_input('tftp server address:')
+ if not copy_patch_file(params, nxapi_handler):
+ print 'Failed to copy patch file'
+ if not list_patch_file(params, nxapi_handler):
+ print 'Failed to copy patch file'
+ else:
+ print 'Patch file:' + params.smu_filename + ' already present'
+ exit(-1)
+ if not list_patch_file(params, nxapi_handler):
+ print 'Failed to copy patch file'
+ exit(-1)
+ elif params.action == 'activate':
+ if not add_module(params, nxapi_handler):
+ print 'Failed to activate module.'
+ exit(-1)
+ if not list_inactive_modules(nxapi_handler):
+ print 'Failed to list inactive modules.'
+ exit(-1)
+ if not activate_patch_file(params, nxapi_handler):
+ print 'Failed to activate patch file.'
+ exit(-1)
+ if not list_active_modules(nxapi_handler):
+ print 'Failed to list active modules'
+ exit(-1)
+ elif params.action == 'deactivate':
+ if not list_active_modules(nxapi_handler):
+ print 'Failed to list active modules'
+ exit(-1)
+ if not deactivate_patch_file(params, nxapi_handler):
+ print 'Failed to deactivate patch file.'
+ exit(-1)
+ if not list_inactive_modules(nxapi_handler):
+ print 'Failed to list inactive modules.'
+ exit(-1)
+ elif params.action == 'remove':
+ if not list_inactive_modules(nxapi_handler):
+ print 'Failed to list inactive modules.'
+ exit(-1)
+ if not remove_modules(params, nxapi_handler):
+ print 'Failed to remove module.'
+ exit(-1)
+ elif params.action == 'commit_active':
+ if not list_active_modules(nxapi_handler):
+ print 'Failed to list active modules'
+ exit(-1)
+ if not commit_active_patch_file(params, nxapi_handler):
+ print 'Failed to commit active modules'
+ exit(-1)
+ elif params.action == 'commit_inactive':
+ if not list_inactive_modules(nxapi_handler):
+ print 'Failed to commit inactive modules'
+ exit(-1)
+ if not commit_inactive_patch_file(params, nxapi_handler):
+ print 'Failed to commit active modules'
+ exit(-1)
+ elif params.action == 'status':
+ if not list_modules_status(nxapi_handler):
+ print 'No modules were found to be inactive, active, or committed'
+ exit(-1)
+ if not show_install_log(nxapi_handler):
+ print 'Failed to get install log.'
+ exit(-1)
+ exit(0)
diff --git a/nexusscripts/off-box/upgrade_patch_mgmt/sw_mgmt.py b/nexusscripts/off-box/upgrade_patch_mgmt/sw_mgmt.py
new file mode 100644
index 00000000..420b96b2
--- /dev/null
+++ b/nexusscripts/off-box/upgrade_patch_mgmt/sw_mgmt.py
@@ -0,0 +1,180 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:OS-Mgmt
+:Box Type:Off-Box
+:Title:Software Management
+:Short Description:This script is to perform Software management operations
+:Long Description:This script is to perform operations like
+ copy, upgrade, downgrade, remove switch images.
+:Input:N9K Address, username, password, tftp_address, image_filename, action
+:Output:status/result of the software management action
+"""
+
+import argparse
+import getpass
+import sys
+
+sys.path.append("../../../nx-os/nxapi/utils")
+from nxapi_utils import *
+from xmltodict import *
+
+
+class Args(object):
+
+ def __init__(self, args):
+ self.n9k = args.hostname
+ self.username = args.username
+ self.password = args.password
+ if not self.password:
+ self.password = getpass.getpass()
+ self.tftp_address = args.tftp_address
+ self.timeout = args.timeout
+ self.image_filename = args.image_filename
+ self.action = args.action
+
+
+def initialize_nxapi_handler(params):
+
+ thisNXAPI = NXAPI()
+ thisNXAPI.set_target_url('http://' + params.n9k +'/ins')
+ thisNXAPI.set_username(params.username)
+ thisNXAPI.set_password(params.password)
+ thisNXAPI.set_timeout(params.timeout)
+ thisNXAPI.set_msg_type('cli_conf')
+ return thisNXAPI
+
+
+def check_status(dict_res):
+
+ if dict_res['ins_api']['outputs']['output']['code'] == '200' and \
+ dict_res['ins_api']['outputs']['output']['msg'] == 'Success':
+ print dict_res['ins_api']['outputs']['output']['body']
+ return True
+ else:
+ print 'Error Msg:' + dict_res['ins_api']['outputs']['output']['msg']
+ print 'Code:' + dict_res['ins_api']['outputs']['output']['code']
+ return False
+
+
+def copy_image_file(params, nxapi_handler):
+
+ print 'copy tftp://'+ params.tftp_address + '/' + params.image_filename +\
+ ' bootflash:// vrf management'
+ nxapi_handler.set_cmd('copy tftp://'+ params.tftp_address + '/' +\
+ params.image_filename + ' bootflash:// vrf management')
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def verify_active_sessions(nxapi_handler):
+ print 'show configuration session summary'
+ nxapi_handler.set_cmd('show configuration session summary')
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def check_image_incompatibility(params, nxapi_handler):
+ nxapi_handler.set_cmd('show incompatibility nxos bootflash:' +\
+ params.image_filename)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def remove_image(params, nxapi_handler):
+ print 'delete bootflash:' + params.image_filename + " no-prompt"
+ nxapi_handler.set_cmd('delete bootflash:' +\
+ params.image_filename + " no-prompt")
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def check_install_all_impact(params, nxapi_handler):
+ print 'show install all impact nxos bootflash:' +\
+ params.image_filename
+ nxapi_handler.set_cmd('show install all impact nxos bootflash:' +\
+ params.image_filename)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def copy_run_cfg_start_cfg(nxapi_handler):
+ print 'copy running-config startup-config'
+ nxapi_handler.set_cmd('copy running-config startup-config')
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def install_all_nxos_image(params, nxapi_handler):
+ print 'install all parallel nxos bootflash:' +\
+ params.image_filename
+ nxapi_handler.set_cmd('install all parallel nxos bootflash:' +\
+ params.image_filename)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 OS software patch management utility.',
+ epilog=""" """)
+
+ parser.add_argument('--n9k', '-i', dest='hostname',
+ help='Nexus 9XXX hostname or ip address', required=True)
+ parser.add_argument('--user', '-u', dest='username',
+ help='Username to login to Nexus 9XXX switch', required=True)
+ parser.add_argument('--password', '-p', dest='password',
+ help='Password to login to Nexus 9XXX switch')
+ parser.add_argument('--tftp-address', '-a', dest='tftp_address',
+ help='Tftp server ip-address.')
+ parser.add_argument('--image_filename', '-f', dest='image_filename',
+ help='Image filename.', required=True)
+ parser.add_argument('--timeout', '-t', dest='timeout',
+ help='Connection Timeout.', type=int, default=600)
+ parser.add_argument('--action', '-o', dest='action',
+ help='Action Upgrade/Downgrade switch image.',
+ required=True, choices = ['copy', 'upgrade', 'downgrade', 'remove'])
+ args = parser.parse_args()
+ return Args(args)
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+ nxapi_handler = initialize_nxapi_handler(params)
+
+ if params.action == 'copy':
+ if not copy_image_file(params, nxapi_handler):
+ print 'Failed to copy image file'
+ exit(-1)
+ elif params.action == 'upgrade':
+ # pre-requisite check before upgrading
+ if not verify_active_sessions(nxapi_handler):
+ print 'Failed to verify active sessions'
+ exit(-1)
+ elif params.action == 'downgrade':
+ if not check_image_incompatibility(params, nxapi_handler):
+ print 'Failed to check image incompatibility'
+ exit(-1)
+ elif params.action == 'remove':
+ if not remove_image(params, nxapi_handler):
+ print 'Failed to remove image'
+ exit(-1)
+
+ if params.action in {'upgrade','downgrade'}:
+ if not check_install_all_impact(params, nxapi_handler):
+ print 'Failed to check install all impact.'
+ exit(-1)
+ if not copy_run_cfg_start_cfg(nxapi_handler):
+ print 'Failed to copy running-config to startup-config.'
+ exit(-1)
+ if not install_all_nxos_image(params, nxapi_handler):
+ print 'Failed to update switch image file.'
+ exit(-1)
+ exit(0)
diff --git a/nexusscripts/on-box/config-mgmt/README.md b/nexusscripts/on-box/config-mgmt/README.md
new file mode 100644
index 00000000..694ea841
--- /dev/null
+++ b/nexusscripts/on-box/config-mgmt/README.md
@@ -0,0 +1,21 @@
+#Nexus 9000 Switch Automation tasks
+
+#Automation of Switch Configuration Category
+Python version > 2.7.*
+
+Nexus Switch version is NXOS: version 6.1(2)I3(1)
+
+
+1. Dynamically update Interface description
+
+ Steps :
+
+ a. Execute the script(interface_desc_cdp.py) on the required switch to update the interface description based on the cdp protocol status for the cisco devices as neighbours.
+ b. command to execute : python filename
+
+
+2. FEX Configuration
+
+ Steps :
+
+ a. Execute the script(fex_config.py) on the required switch to check the FEX configuration status.
diff --git a/nexusscripts/on-box/config-mgmt/fex_config.py b/nexusscripts/on-box/config-mgmt/fex_config.py
new file mode 100644
index 00000000..daaa52d8
--- /dev/null
+++ b/nexusscripts/on-box/config-mgmt/fex_config.py
@@ -0,0 +1,143 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:On-Box
+:Title:FEX configuration
+:Short Description:To dynamically configure FEX
+:Long Description:Check the FEX state.If not installed,install the FEX.
+If not enabled ,enable the FEX.
+:Input:command to check the FEX installation and based on the command output,
+ install the FEX.Interfaces to configure to the FEX.
+:Output:FEX should be enabled and interfaces should be configured.
+"""
+
+import os,sys
+import json
+import argparse
+from cli import *
+
+
+class Args(object):
+
+ def __init__(self, args):
+ self.interface_type = args.interface_type
+ self.interface_number = args.interface_number
+ self.fex_number = args.fex_number
+
+
+
+"""
+
+Class to install/enable FEX on the Nexus Switch
+"""
+
+class FEX_Config:
+
+ earlierstat = ''; currentstat = '';
+
+
+ def initialize_args(self):
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 FEX configuration mgmt.',
+ epilog=""" """)
+
+ parser.add_argument('--interface-type', '-t', dest='interface_type',
+ help='Interface type',
+ choices={'ethernet', 'port-channel'})
+ parser.add_argument('--interface-number', '-s', dest='interface_number',
+ help="ethernet interface slot/port")
+ parser.add_argument('--fex-number', '-f', dest='fex_number',
+ help="fex number")
+
+ args = parser.parse_args()
+ return Args(args)
+
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+ global osversion;
+ versioncmd = "show version"
+ out = json.loads(clid(versioncmd))
+ chassis_id = out['chassis_id']
+ osversion = out['rr_sys_ver']
+ cpu_name = out['cpu_name']
+ memory = out['memory']
+ processor_board = out['proc_board_id']
+ device = out['host_name']
+ bootflash = out['bootflash_size']
+
+ print "Nexus Switch OS version is :" , osversion
+ print "Chassis ID is :", chassis_id
+ print cpu_name + "with" + str(memory) + "KB of memory"
+ print "Processor Board ID is " + processor_board
+
+ print "Device Name : " + device
+ print "Bootflash : " + str(bootflash)
+
+
+ def fex_status(self):
+ fexob = FEX_Config()
+ global cdp_dict
+ out = json.loads(clid("show feature-set fex"))
+ status = out['TABLE-cfcFeatureSetTable']['cfcFeatureSetOpStatus']
+ FEX_Config.earlierstat = "On " + osversion + " Nexus Switch FEX is " + status
+ print FEX_Config.earlierstat
+ fexob.fex_update(status)
+
+ def fex_update(self, stat):
+
+ if ((stat == 'disabled') or (stat == 'installed')) :
+ cli('config terminal ; feature-set fex')
+ FEX_Config.currentstat = "FEX is now enabled "
+ print FEX_Config.currentstat
+
+ if (stat == 'uninstalled') :
+ cmd = "conf t" + ' ' + " ;" + ' ' + "install feature-set fex" + ' ' + ";" + ' ' + "feature-set fex"
+
+ cli(cmd)
+
+ FEX_Config.currentstat = "FEX is installed and enabled"
+ print FEX_Config.currentstat
+
+ def fex_config(self, params):
+
+ try:
+ cmd = "config terminal" + ' ' + ";" + ' ' + 'interface' + ' ' + params.interface_type + params.interface_number + ' ' + ";" + ' ' + "switchport" + ' ' + ";"
+ "switchport mode fex-fabric" + ' ' + ";" + ' ' + "fex associate" + ' ' + params.fex_number + ' ' + ";" + ' '
+
+ cli(cmd)
+ except Exception as e:
+ #print (e)
+ if (e):
+ print " Interface " + params.interface_type + ' ' + params.interface_number + ' ' + "is not configured to FEX.Check the Interface and FEX numbers are valid."
+
+ print "The configured interfaces are:"
+ out = json.loads(clid("show interface fex-fabric"))
+ #print out
+ status = out['TABLE_fex_fabric']['ROW_fex_fabric']
+ if (isinstance(status, list)):
+ for i in status:
+ for key,value in i.items():
+ if (key == 'fbr_port'):
+ print value
+ elif (isinstance(status, dict)):
+ for key,value in status.items():
+ if (key == 'fbr_port'):
+ print value
+
+ else:
+ print "Not implemented for this response type"
+
+
+
+
+
+
+if __name__ == '__main__':
+ systemob = FEX_Config()
+ params = systemob.initialize_args()
+ systemob.nexus_version()
+ systemob.fex_status()
+ systemob.fex_config(params)
+
diff --git a/nexusscripts/on-box/config-mgmt/interface_desc_cdp.py b/nexusscripts/on-box/config-mgmt/interface_desc_cdp.py
new file mode 100644
index 00000000..95763056
--- /dev/null
+++ b/nexusscripts/on-box/config-mgmt/interface_desc_cdp.py
@@ -0,0 +1,120 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:On-Box
+:Title:Interface Description configuration
+:Short Description:To dynamically configure interface descriptions
+:Long Description:Check the CDP state and modify the interface description accordingly.
+:Input:command to check the CDP state and based on the command output,
+ modify the description of the interface
+:Output:interface description should be updated
+"""
+
+import os
+from cli import *
+import sys
+
+"""
+
+Class to update the interface description based on the
+CDP state
+"""
+
+class Interface_Desc:
+
+ interface_message = {}
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+ versioncmd = "show version"
+ out = json.loads(clid(versioncmd))
+ chassis_id = out['chassis_id']
+ osversion = out['rr_sys_ver']
+ cpu_name = out['cpu_name']
+ memory = out['memory']
+ processor_board = out['proc_board_id']
+ device = out['host_name']
+ bootflash = out['bootflash_size']
+
+ print "Nexus Switch OS version is :" , osversion
+ print "Chassis ID is :", chassis_id
+ print cpu_name + "with" + str(memory) + "KB of memory"
+ print "Processor Board ID is " + processor_board
+
+ print "Host Name : " + device
+ print "Bootflash : " + str(bootflash) + ' ' + "KB"
+ print "\n"
+
+ def cdp_status(self):
+ intob = Interface_Desc()
+
+ #check CDP is enabled or not
+ cdp_stat = "show cdp global"
+ stat = json.loads(clid(cdp_stat))
+
+ if (stat['cdp_global_enabled'] == 'enabled'):
+ print "CDP is enabled on the Host Switch"
+ cdp_nei = "show cdp nei"
+ status = json.loads(clid(cdp_nei))
+ status_list = status['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info']
+ cdp_dict = {}
+
+ if (isinstance(status_list, list)):
+ for i in status_list:
+ for key,value in i.items():
+ if (key == 'device_id'):
+ cdp_dict.update({key:value})
+ if (key == 'intf_id'):
+ cdp_dict.update({key:value})
+ if (key == 'port_id'):
+ cdp_dict.update({key:value})
+ if (key == 'capability'):
+ cdp_dict.update({key:value})
+ intob.updateinterface(cdp_dict)
+ elif (isinstance(status_list, dict)):
+ for key,value in status_list.items():
+ if (key == 'device_id'):
+ cdp_dict.update({key:value})
+ if (key == 'intf_id'):
+ cdp_dict.update({key:value})
+ if (key == 'port_id'):
+ cdp_dict.update({key:value})
+ if (key == 'capability'):
+ cdp_dict.update({key:value})
+ intob.updateinterface(cdp_dict)
+ else:
+ print "Not implemented for this response type"
+
+ else:
+ print "CDP is not enabled on the Host Switch.Please check the CDP manual to enable it. "
+ exit(1)
+
+ #update the interface description
+ def updateinterface(self, data):
+ for key,value in data.iteritems():
+ if (key == 'intf_id'):
+ cmd1 = "interface" + ' ' + value
+ desc = "description" + ' ' + "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+ msg = "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+
+ cmd = "conf t" + ' ' + " ;" + ' ' + cmd1 + ' ' + ";" + ' ' + desc
+ cli(cmd)
+ print "\n"
+ print "Interface" + ' ' + data['intf_id'] + ' ' + "description is updated as : " + ' ' + msg
+ if (data['capability']):
+ print "Neighbor device" + ' ' + data['device_id'] + ' ' + "is capable as : "
+ for i in data['capability']:
+ print str(i)
+
+ #print data['capability']
+
+
+
+if __name__ == '__main__':
+ interfaceob = Interface_Desc()
+ interfaceob.nexus_version()
+ interfaceob.cdp_status()
+
+
+
+
diff --git a/nexusscripts/on-box/config-mgmt/interface_desc_lldp.py b/nexusscripts/on-box/config-mgmt/interface_desc_lldp.py
new file mode 100644
index 00000000..41050d63
--- /dev/null
+++ b/nexusscripts/on-box/config-mgmt/interface_desc_lldp.py
@@ -0,0 +1,128 @@
+"""script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:On-Box
+:Title:Interface Description configuration
+:Short Description:To dynamically configure interface descriptions
+:Long Description:Check the LLDP state and modify the interface description accordingly.
+:Input:command to check the LLDP state and based on the command output,
+ modify the description of the interface
+:Output:interface description should be updated
+"""
+
+import os
+from cli import *
+import sys
+
+"""
+
+Class to update the interface description based on the
+LLDP state
+"""
+
+class Interface_Desc:
+
+ interface_message = {}
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+ versioncmd = "show version"
+ out = json.loads(clid(versioncmd))
+ chassis_id = out['chassis_id']
+ osversion = out['rr_sys_ver']
+ cpu_name = out['cpu_name']
+ memory = out['memory']
+ processor_board = out['proc_board_id']
+ device = out['host_name']
+ bootflash = out['bootflash_size']
+
+ print "Nexus Switch OS version is :" , osversion
+ print "Chassis ID is :", chassis_id
+ print cpu_name + "with" + str(memory) + "KB of memory"
+ print "Processor Board ID is " + processor_board
+
+ print "Host Name : " + device
+ print "Bootflash : " + str(bootflash) + ' ' + "KB"
+ print "\n"
+
+
+ def lldp_status(self):
+
+ intob = Interface_Desc()
+
+ #check lldp is enabled or not
+ lldp_stat = "show lldp neighbors"
+ try:
+ stat = json.loads(clid(lldp_stat))
+ except:
+ print "LLDP is not enabled on the host switch"
+ exit(1)
+ if (stat):
+ print "LLDP is enabled on the host switch"
+ lldp_nei = "show lldp neighbors"
+ status = json.loads(clid(lldp_nei))
+ #print status
+ status_list = status['TABLE_nbor']['ROW_nbor']
+ lldp_dict = {}
+
+ if (isinstance(status_list, list)):
+ for i in status_list:
+ for key,value in i.items():
+ if (key == 'chassis_id'):
+ lldp_dict.update({'device_id':value})
+ if (key == 'l_port_id'):
+ lldp_dict.update({'intf_id':value})
+ if (key == 'port_id'):
+ lldp_dict.update({key:value})
+ if (key == 'capability'):
+ lldp_dict.update({key:''})
+ intob.updateinterface(lldp_dict)
+
+ elif (isinstance(status_list, dict)):
+ for key,value in status_list.items():
+ if (key == 'chassis_id'):
+ lldp_dict.update({'device_id':value})
+ if (key == 'l_port_id'):
+ lldp_dict.update({'intf_id':value})
+ if (key == 'port_id'):
+ lldp_dict.update({key:value})
+ if (key == 'capability'):
+ lldp_dict.update({key:''})
+
+ intob.updateinterface(lldp_dict)
+ else:
+ print "Not implemented for this response type"
+
+ else:
+ print "LLDP is not enabled on the Host Switch."
+ exit(1)
+
+
+
+ #update the interface description
+ def updateinterface(self, data):
+ #print data
+ for key,value in data.iteritems():
+ if (key == 'intf_id'):
+ cmd1 = "interface" + ' ' + value
+ desc = "description" + ' ' + "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+ msg = "Connected to device" + ' ' + data['device_id'] + ' ' + "on" + ' ' + data['port_id']
+
+ cmd = "conf t" + ' ' + " ;" + ' ' + cmd1 + ' ' + ";" + ' ' + desc
+ cli(cmd)
+ print "\n"
+ print "Interface" + ' ' + data['intf_id'] + ' ' + "description is updated as : " + ' ' + msg
+ #if (data['capability']):
+ # print "Neighbor device" + ' ' + data['device_id'] + ' ' + "is capable as : "
+ #for i in data['capability']:
+ # print str(i)
+
+ # print data['capability']
+
+
+
+if __name__ == '__main__':
+ interfaceob = Interface_Desc()
+ interfaceob.nexus_version()
+ interfaceob.lldp_status()
+
diff --git a/nexusscripts/on-box/config-mgmt/l2_vlan_mgmt.py b/nexusscripts/on-box/config-mgmt/l2_vlan_mgmt.py
new file mode 100644
index 00000000..4fa486f6
--- /dev/null
+++ b/nexusscripts/on-box/config-mgmt/l2_vlan_mgmt.py
@@ -0,0 +1,145 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:On-Box
+:Title:VLAN Configuration Management
+:Short Description:This script is to perform L2 VLAN operations
+:Long Description:This script is to perform configuration operations
+ of L2 VLAN interfaces
+:Input:N9K Address, username, password, L2 VLAN parameters
+:Output:status/result of the L2 VLAN configuration parameters
+"""
+
+import argparse
+import sys
+from cli import *
+
+cmd_config_terminal = "config terminal ;"
+cmd_int_ethernet = "interface ethernet %s/%s ;"
+cmd_int_port_channel = "interface port-channel %s ;"
+cmd_int_no_shutdown = "no shutdown ;"
+cmd_switchport_mode = "switchport mode %s ;"
+cmd_switchport_access_vlan = "switchport access vlan %s ;"
+cmd_switchport_host = "switchport host ;"
+cmd_switchport = "switchport ;"
+cmd_switchport_trunk_native = "switchport trunk native vlan %s ;"
+cmd_switchport_trunk_allowed_vlan = "switchport trunk allowed vlan %s %s ;"
+cmd_default_int = "default interface int-if %s ;"
+cmd_switchport_autostate_exclude = "switchport autostate exclude ;"
+cmd_switchport_autostate_exclude_vlan =\
+ "switchport autostate exclude vlan %s ;"
+cmd_svi_autostate_disable = "system default interface-vlan no autostate ;"
+
+cmd_vlan_tag_native = "vlan dot1q tag native ;"
+cmd_sys_default_port_mode_2_l2 = "system default switchport ;"
+
+cmd_copy_running_startup = "copy running-config startup-config ;"
+cmd_show_interface = "show running-config interface %s %s ;"
+
+class Args(object):
+
+ def __init__(self, args):
+ self.vlan_list = args.vlan_list
+ self.int_type = args.int_type
+ self.port_channel_id = args.port_channel_id
+ self.slot = args.slot
+ self.port = args.port
+ self.switchport_mode = args.switchport_mode
+ self.trunk_allowed_vlan_oper = args.trunk_allowed_vlan_oper
+ self.trunk_native_id = args.trunk_native_id
+ self.tag_native_vlan = args.tag_native_vlan
+
+
+def create_l2_interface(params):
+
+ cmd_str = cmd_config_terminal
+ if params.tag_native_vlan:
+ cmd_str += cmd_vlan_tag_native
+
+ if params.int_type == 'ethernet':
+ cmd_str += cmd_int_ethernet % (params.slot, params.port)
+ if params.int_type == 'port-channel':
+ cmd_str += cmd_int_port_channel % (params.port_channel_id)
+
+ if params.int_type:
+ cmd_str += cmd_switchport
+ cmd_str += cmd_int_no_shutdown
+
+ if params.switchport_mode == 'access':
+ cmd_str += cmd_switchport_mode % (params.switchport_mode)
+ cmd_str += cmd_switchport_access_vlan % (params.vlan_list)
+ elif params.switchport_mode == 'host':
+ cmd_str += cmd_switchport_host
+ elif params.switchport_mode == 'trunk':
+ cmd_str += cmd_switchport_mode % (params.switchport_mode)
+ if params.trunk_native_id:
+ cmd_str += cmd_switchport_trunk_native % (params.trunk_native_id)
+ if params.trunk_allowed_vlan_oper in {'add', 'remove', 'except'}:
+ cmd_str += cmd_switchport_trunk_allowed_vlan %\
+ (params.trunk_allowed_vlan_oper, params.vlan_list)
+ elif params.trunk_allowed_vlan_oper in {'all', 'none'}:
+ cmd_str += cmd_switchport_trunk_allowed_vlan %\
+ (params.trunk_allowed_vlan_oper, ' ')
+ else:
+ cmd_str += cmd_switchport_trunk_allowed_vlan %\
+ (params.vlan_list, ' ')
+
+ cmd_str += cmd_copy_running_startup
+
+ print cmd_str
+ return_xml = cli(cmd_str)
+ print return_xml
+
+
+def show_interface(params):
+ cmd_str = ''
+ if params.int_type == 'ethernet':
+ cmd_str += cmd_show_interface %\
+ (params.int_type, "%s/%s" %(params.slot, params.port))
+ elif params.int_type == 'port-channel':
+ cmd_str += cmd_show_interface % (params.int_type, params.port_channel_id)
+ print cmd_str
+ return_xml = cli(cmd_str)
+ print return_xml
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 L2 VLAN interface configuration mgmt.',
+ epilog=""" """)
+
+ parser.add_argument('--interface_type', '-t', dest='int_type',
+ help='Interface type',
+ choices={'ethernet', 'port-channel'})
+ parser.add_argument('--slot-id', '-s', dest='slot',
+ help="ethernet interface slot-id")
+ parser.add_argument('--port-id', '-p', dest='port',
+ help="ethernet interface port-id")
+ parser.add_argument('--port-channel-id', '-n', dest='port_channel_id',
+ help='port-channel id')
+ parser.add_argument('--switchport-mode', '-m', dest='switchport_mode',
+ help='switchport mode \'access|trunk|host\'',
+ choices={'access', 'trunk', 'host'})
+ parser.add_argument('--trunk-allowed-vlan-oper', '-o',
+ dest='trunk_allowed_vlan_oper', help='trunk allowed vlan oper',
+ choices={'add', 'remove', 'except', 'all', 'none'}),
+ parser.add_argument('--vlan-list', '-v', dest='vlan_list',
+ help='VLAN ID/list')
+ parser.add_argument('--trunk-native-vlan-id', '-k', dest='trunk_native_id',
+ help='Trunk native VLAN ID')
+ parser.add_argument('--tag-native-vlan-traffic', '-r',
+ dest='tag_native_vlan',
+ help='Tag native VLAN traffic', type=bool, default=False)
+
+ args = parser.parse_args()
+ return Args(args)
+
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+ create_l2_interface(params)
+ show_interface(params)
+
+ exit(0)
diff --git a/nexusscripts/on-box/config-mgmt/l3_vlan_mgmt.py b/nexusscripts/on-box/config-mgmt/l3_vlan_mgmt.py
new file mode 100644
index 00000000..4060e4f1
--- /dev/null
+++ b/nexusscripts/on-box/config-mgmt/l3_vlan_mgmt.py
@@ -0,0 +1,164 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:On-Box
+:Title:VLAN Configuration Management
+:Short Description:This script is to perform L3 VLAN operations
+:Long Description:This script is to perform configuration operations
+ of L3 VLAN interfaces
+:Input:N9K Address, username, password, L3 VLAN parameters
+:Output:status/result of the L3 VLAN configuration parameters
+"""
+
+import argparse
+from cli import *
+import sys
+
+cmd_negate_option = "no"
+cmd_config_terminal = "config terminal ;"
+cmd_int_ethernet = "interface ethernet %s ;"
+cmd_int_no_shutdown = "no shutdown ;"
+cmd_no_switchport = "no switchport ;"
+cmd_feature_int_vlan = "feature interface-vlan ;"
+cmd_create_svi_int = "interface vlan %s ;"
+cmd_ip_addr_mask = "ip address %s %s ;"
+cmd_ip_addr_len = "ip address %s/%s ;"
+cmd_ipv6_addr_len = "ipv6 address %s/%s ;"
+cmd_ipv6_addr_link_local = "ipv6 address use-link-local-only ;"
+cmd_encap_dot1q_vlanid = "encapsulation dot1Q %s ;"
+cmd_show_interfaces = "show interfaces ;"
+
+cmd_int_port_channel = "interface port-channel %s ;"
+cmd_int_vlan_interface = "interface vlan %s ;"
+cmd_no_shutdown = "no shutdown ;"
+cmd_show_vlan_vlanid = "show interface vlan %s ;"
+cmd_create_loopback_int = "interface loopback %s ;"
+cmd_show_loopback_int = "show interface loopback %s ;"
+
+cmd_add_vrf_member = "vrf member %s ;"
+cmd_show_vrf = "show vrf %s interface %s %s ;"
+cmd_show_interface = "show interface %s %s ;"
+
+cmd_copy_running_startup = "copy running-config startup-config ;"
+
+
+
+class Args(object):
+
+ def __init__(self, args):
+ self.vlan_id = args.vlan_id
+ self.int_type = args.int_type
+ self.slot = args.slot
+ self.port = args.port
+ self.port_channel_id = args.port_channel_id
+ self.dot1q_vlanid = args.dot1q_vlanid
+ self.loopback_instance = args.loopback_instance
+ self.ip_addr = args.ip_addr
+ self.ip_len = args.ip_len
+ self.ip_mask = args.ip_mask
+ self.ipv6_addr = args.ipv6_addr
+ self.ipv6_len = args.ipv6_len
+ self.ipv6_link_local = args.ipv6_link_local
+ self.vrf_member = args.vrf_member
+
+
+def create_l3_interface(params):
+
+ cmd_str = cmd_config_terminal
+ if params.int_type == 'ethernet':
+ cmd_str += cmd_int_ethernet % (params.slot + "/" + params.port)
+ cmd_str += cmd_no_switchport
+ if params.dot1q_vlanid:
+ cmd_str += cmd_encap_dot1q_vlanid % (params.dot1q_vlanid)
+ elif params.int_type == 'port-channel':
+ cmd_str += cmd_int_port_channel % (params.port_channel_id)
+ cmd_str += cmd_encap_dot1q_vlanid % (params.dot1q_vlanid)
+ elif params.int_type == 'vlan':
+ cmd_str += cmd_int_vlan_interface % (params.vlan_id)
+ cmd_str += cmd_no_shutdown
+ elif params.int_type == 'loopback':
+ cmd_str += cmd_create_loopback_int % (params.loopback_instance)
+
+ if params.ip_addr and params.ip_len:
+ cmd_str += cmd_ip_addr_len % (params.ip_addr, params.ip_len)
+ elif params.ip_addr and params.ip_mask:
+ cmd_str += cmd_ip_addr_mask % (params.ip_addr, params.ip_mask)
+
+ if params.ipv6_addr and params.ipv6_len:
+ cmd_str += cmd_ipv6_addr_len % (params.ipv6_addr, params.ipv6_len)
+ if params.ipv6_link_local:
+ cmd_str += cmd_ipv6_addr_link_local
+
+ if params.vrf_member:
+ cmd_str += cmd_add_vrf_member % (params.vrf_member)
+
+ cmd_str += cmd_int_no_shutdown
+ cmd_str += cmd_copy_running_startup
+
+ print cmd_str
+ return_xml = cli(cmd_str)
+ print return_xml
+
+
+def show_interface(params):
+ cmd_str = ''
+ if params.int_type == 'ethernet':
+ cmd_str += cmd_show_interface %\
+ (params.int_type, "%s/%s" %(params.slot, params.port))
+ elif params.int_type == 'port-channel':
+ cmd_str += cmd_show_interface % params.int_type, params.port_channel_id
+ elif params.int_type == 'vlan':
+ cmd_str += cmd_show_interface % params.int_type, params.vlan_id
+ elif params.int_type == 'loopback':
+ cmd_str += cmd_show_interface % params.int_type, params.loopback_instance
+ print cmd_str
+ return_xml = cli(cmd_str)
+ print return_xml
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 L3 VLAN interface configuration mgmt.',
+ epilog=""" """)
+
+ parser.add_argument('--interface_type', '-t', dest='int_type',
+ help='Interface type',
+ choices={'ethernet', 'port-channel', 'vlan', 'loopback'})
+ parser.add_argument('--slot-id', '-s', dest='slot',
+ help="ethernet interface slot-id")
+ parser.add_argument('--port-id', '-p', dest='port',
+ help="ethernet interface port-id")
+ parser.add_argument('--port-channel-id', '-n', dest='port_channel_id',
+ help='Encaptulation vlan-id')
+ parser.add_argument('--encap_vlanid', '-e', dest='dot1q_vlanid',
+ help='Encaptulation vlan-id')
+ parser.add_argument('--vlanid', '-v', dest='vlan_id',
+ help='VLAN id')
+ parser.add_argument('--loopback_instnace_id', '-o', dest='loopback_instance',
+ help='Loopback interface instance id')
+ parser.add_argument('--ip-address', '-4', dest='ip_addr',
+ help='IPv4 address')
+ parser.add_argument('--ip-address-length', '-l', dest='ip_len',
+ help='IPv4 address length')
+ parser.add_argument('--ip-address-mask', '-m', dest='ip_mask',
+ help='IPv4 address length')
+ parser.add_argument('--ipv6-address', '-6', dest='ipv6_addr',
+ help='IPv6 address')
+ parser.add_argument('--ipv6-address-length', '-k', dest='ipv6_len',
+ help='IPv6 address length')
+ parser.add_argument('--ipv6-use-link-local-address', '-q', dest='ipv6_link_local',
+ help='IPv6 address length', type=bool, default=False)
+ parser.add_argument('--vrf-member-id', '-r', dest='vrf_member',
+ help='IPv6 address length')
+
+ args = parser.parse_args()
+ return Args(args)
+
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+ create_l3_interface(params)
+ show_interface(params)
+ exit(0)
diff --git a/nexusscripts/on-box/config-mgmt/transceiver.py b/nexusscripts/on-box/config-mgmt/transceiver.py
new file mode 100644
index 00000000..71f6c922
--- /dev/null
+++ b/nexusscripts/on-box/config-mgmt/transceiver.py
@@ -0,0 +1,149 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:On-Box
+:Title:Transceiver auto speed detection and setup
+:Short Description:This script is to monitor transceiver speed at all the interfaces of switch.
+:Long Description:Helps in monitoring any changes in speed at any Interfaces of the switch by setting specific supported speed of the transceiver.
+:Input:No Input
+:Output:No Output
+"""
+from __future__ import print_function
+import os,sys
+import json
+import re
+from cli import *
+
+cmd_config_terminal = "config terminal ;"
+cmd_str_ethernet = "interface ethernet %s ;"
+cmd_speed_hundred = " speed 100 ;"
+cmd_speed_1k = " speed 1000 ;"
+cmd_speed_10k = " speed 10000 ;"
+cmd_speed_100k = " speed 100000 ;"
+cmd_speed_40k = " speed 40000 ;"
+cmd_speed_auto = " speed auto ;"
+cmd_str_no_shutdown = " no shutdown ;"
+cmd_transceiver_speed = "show interface ethernet %s/%s transceiver ;"
+cmd_end = " end ;"
+cmd_copy_running_startup = "copy running-config startup-config ;"
+cmd_show_interface = "show running-config interface %s %s ;"
+
+
+class Interface_Monit:
+
+ interface_list = []; cmd_str = '';
+
+ #create a command to get the interface status
+ def interfacemonit(self):
+ interfaceobj = Interface_Monit()
+
+
+ out = json.loads(clid("show interface status"))
+ Interface_Monit.interface_list = out['TABLE_interface']['ROW_interface']
+
+
+ for i in Interface_Monit.interface_list:
+ for key,value in i.items():
+ if (key == 'interface'):
+ m = re.search('Ethernet(.*)', value)
+ if m:
+ found = m.group(1)
+ slotport = found.split('/')
+
+ cmd = "show interface ethernet " + str(slotport[0]) + "/" + str(slotport[1] + " transceiver")
+ out = json.loads(clid(cmd))
+ status = out['TABLE_interface']['ROW_interface']['sfp']
+ if (status == "present" ):
+ bitrate = out['TABLE_interface']['ROW_interface']['nom_bitrate']
+ interfaceobj.transceiver(slotport[0], slotport[1], int(bitrate))
+ else:
+ pass
+
+
+
+ # Get the Nexus Transceiver info
+ def transceiver(self, i, j, bitrate):
+ interfaceobj = Interface_Monit()
+ cmd_str = ''
+ print ("\nNominal bitrate/Transceiver speed at interface " + str(i) + "/" + str(j) + " = " + str(bitrate))
+ if (bitrate >= 100 and bitrate <= 1000):
+ cmd_str += cmd_config_terminal
+ cmd_str += cmd_str_ethernet % (str(i) +"/"+ str(j))
+ cmd_str += cmd_speed_hundred
+ cmd_str += cmd_str_no_shutdown
+ cmd_str += cmd_end
+ return_xml = cli(cmd_str)
+ print (return_xml.replace ("ERROR", "NOTE"), end = '')
+ err = re.search('ERROR(.*)', return_xml)
+ if err:
+ interfaceobj.auto(i,j)
+
+ elif (bitrate >= 1000 and bitrate <= 10000):
+ cmd_str += cmd_config_terminal
+ cmd_str += cmd_str_ethernet % (str(i) +"/"+ str(j))
+ cmd_str += cmd_speed_1k
+ cmd_str += cmd_str_no_shutdown
+ cmd_str += cmd_end
+ return_xml = cli(cmd_str)
+ err = re.search('ERROR(.*)', return_xml)
+ print (return_xml.replace ("ERROR", "NOTE"), end = '')
+ if err:
+ interfaceobj.auto(i,j)
+
+ elif (bitrate >= 10000 and bitrate <= 40000):
+ cmd_str += cmd_config_terminal
+ cmd_str += cmd_str_ethernet % (str(i) +"/"+ str(j))
+ cmd_str += cmd_speed_10k
+ cmd_str += cmd_str_no_shutdown
+ cmd_str += cmd_end
+ return_xml = cli(cmd_str)
+ err = re.search('ERROR(.*)', return_xml)
+ print (return_xml.replace ("ERROR", "NOTE"), end = '')
+ if err:
+ interfaceobj.auto(i,j)
+
+ elif (bitrate >= 40000 and bitrate <= 100000):
+ cmd_str += cmd_config_terminal
+ cmd_str += cmd_str_ethernet % (str(i) +"/"+ str(j))
+ cmd_str += cmd_speed_40k
+ cmd_str += cmd_str_no_shutdown
+ cmd_str += cmd_end
+ return_xml = cli(cmd_str)
+ err = re.search('ERROR(.*)', return_xml)
+ print (return_xml.replace ("ERROR", "NOTE"), end = '')
+ if err:
+ interfaceobj.auto(i,j)
+
+ elif (bitrate >= 100000):
+ cmd_str += cmd_config_terminal
+ cmd_str += cmd_str_ethernet % (str(i) +"/"+ str(j))
+ cmd_str += cmd_speed_100k
+ cmd_str += cmd_str_no_shutdown
+ cmd_str += cmd_end
+ return_xml = cli(cmd_str)
+ err = re.search('ERROR(.*)', return_xml)
+ print (return_xml.replace ("ERROR", "NOTE"), end = '')
+ if err:
+ interfaceobj.auto(i,j)
+
+ else:
+ interfaceobj.auto(i,j)
+
+
+ def auto(self, i, j):
+ interfaceobj = Interface_Monit()
+ cmd_str = ''
+ cmd_str += cmd_config_terminal
+ cmd_str += cmd_str_ethernet % (str(i) +"/"+ str(j))
+ cmd_str += cmd_speed_auto
+ cmd_str += cmd_str_no_shutdown
+ cmd_str += cmd_end
+ print ("Changing Speed to AUTO")
+ return_xml = cli(cmd_str)
+ print (return_xml.replace ("ERROR", "NOTE"), end = '')
+
+if __name__ == '__main__':
+ interfaceobj = Interface_Monit()
+ interfaceobj.interfacemonit()
+ #exit(0)
+
diff --git a/nexusscripts/on-box/config-mgmt/vlan_config.py b/nexusscripts/on-box/config-mgmt/vlan_config.py
new file mode 100644
index 00000000..199038f1
--- /dev/null
+++ b/nexusscripts/on-box/config-mgmt/vlan_config.py
@@ -0,0 +1,105 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Config-Mgmt
+:Box Type:On-Box
+:Title:VLAN Configuration Management
+:Short Description:This script is to perform VLAN operations
+:Long Description:This script is to perform configuration operations
+ of VLAN interfaces
+:Input:N9K Address, username, password, VLAN parameters
+:Output:status/result of the VLAN configuration parameterssssss
+"""
+
+import argparse
+from cli import *
+import sys
+from xml.dom import minidom
+
+cmd_config_terminal = "config terminal ;"
+cmd_vlan_id_range = "vlan %s ;"
+cmd_no_vlan_id_range = "no vlan %s ;"
+cmd_vlan_media = "media enet ;"
+cmd_vlan_name = "name %s ;"
+cmd_vlan_state = "state %s ;"
+cmd_vlan_no_shutdown = "no shutdown ;"
+cmd_vlan_long_name = "system vlan long-name ;"
+
+cmd_copy_running_startup = "copy running-config startup-config ;"
+
+cmd_vlan_show = "show running-config vlan %s"
+cmd_vlan_summary = "show vlan summary"
+cmd_vtp_status = "show vtp status"
+
+
+class Args(object):
+
+ def __init__(self, args):
+ self.vlan = args.vlan
+ self.vlan_name = args.vlan_name
+ self.vlan_state = args.vlan_state
+ self.action = args.action
+ self.vlan_shutdown = args.vlan_shutdown
+
+
+def configure_vlan(params):
+
+ cmd_str = cmd_config_terminal
+ if params.action == 'configure':
+ cmd_str += cmd_vlan_id_range % (params.vlan)
+ if params.vlan_name:
+ cmd_str += cmd_vlan_name % (params.vlan_name)
+ if params.vlan_state:
+ cmd_str += cmd_vlan_state % (params.vlan_state)
+ if not params.vlan_shutdown:
+ cmd_str += cmd_vlan_no_shutdown
+ elif params.action == 'remove':
+ cmd_str += cmd_no_vlan_id_range % (params.vlan)
+
+ cmd_str += cmd_copy_running_startup
+
+ print cmd_str
+ return_xml = cli(cmd_str)
+ print return_xml
+ return True
+
+
+def show_vlan(params):
+ cmd_str = cmd_vlan_show % (params.vlan)
+
+ print cmd_str
+ return_xml = cli(cmd_str)
+ print return_xml
+ return True
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 VLAN configuration',
+ epilog=""" """)
+
+ parser.add_argument('--vlan', '-v', dest='vlan',
+ help='VLAN id/range', required=True)
+ parser.add_argument('--vlan-name', '-n', dest='vlan_name',
+ help='VLAN name')
+ parser.add_argument('--state', '-s', dest='vlan_state',
+ help='VLAN state', choices={'active', 'suspend'}, default='active')
+ parser.add_argument('--shutdown', '-d', dest='vlan_shutdown',
+ help='VLAN state', type=bool, default=False)
+ parser.add_argument('--action', '-o', dest='action',
+ help='VLAN state', choices={'configure', 'remove', 'show'})
+
+ args = parser.parse_args()
+ return Args(args)
+
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+ if params.action in {'remove', 'configure'}:
+ configure_vlan(params)
+ show_vlan(params)
+ else:
+ show_vlan(params)
+
+ exit(0)
diff --git a/nexusscripts/on-box/monitoring/README.md b/nexusscripts/on-box/monitoring/README.md
new file mode 100644
index 00000000..817ee440
--- /dev/null
+++ b/nexusscripts/on-box/monitoring/README.md
@@ -0,0 +1,24 @@
+#Nexus 9000 Switch Automation tasks
+
+#Automation of Switch Monitoring Category
+Python version > 2.7.*
+
+Nexus Switch version is NXOS: version 6.1(2)I3(1)
+
+
+1. Interface monitoring
+
+ Steps :
+
+ a. execute the script (interface_monitor.py) to monitor the interfaces for the input and output errors.
+ b. command to execute: "python filename"
+
+
+
+2. Sytem-Level Resources monitoring
+
+ Steps :
+
+ a. execute the script (systemresc_monitor.py) to monitor the system-level resources e.g cpu-utilization,memory usage etc.
+ b. command to execute: "python filename"
+
diff --git a/nexusscripts/on-box/monitoring/interface_monitor.py b/nexusscripts/on-box/monitoring/interface_monitor.py
new file mode 100644
index 00000000..972e673e
--- /dev/null
+++ b/nexusscripts/on-box/monitoring/interface_monitor.py
@@ -0,0 +1,181 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Monitoring
+:Box Type:On-Box
+:Title:Interface Monitoring
+:Short Description:This script is to monitor Interface counters.
+:Long Description:This script is to monitor Interface counters like
+Errors, Drops, Utilization etc.
+:Input:command to check the interface status
+ e.g show interface ethernet 1/1
+:Output:Details of Drops,Errors and Utilization for all the interfaces
+"""
+
+import os,sys
+import json
+import re
+from cli import *
+
+
+
+
+"""
+
+Class to monitor Interfaces for Input/Output
+errors on the Nexus Switch
+"""
+
+class Interface_Monit:
+
+
+ in_err = {}; out_err = {}; interface_list = []; rx_tx_dict = {};
+
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+ global osversion;
+ versioncmd = "show version"
+ out = json.loads(clid(versioncmd))
+ chassis_id = out['chassis_id']
+ osversion = out['rr_sys_ver']
+ cpu_name = out['cpu_name']
+ memory = out['memory']
+ processor_board = out['proc_board_id']
+ device = out['host_name']
+ bootflash = out['bootflash_size']
+
+ print "Nexus Switch OS version is :" , osversion
+ print "Chassis ID is :", chassis_id
+ print cpu_name + ' ' + "with" + ' ' + str(memory) + ' ' + "KB of memory"
+ print "Processor Board ID is " + processor_board
+
+ print "Host Name : " + device
+ print "Bootflash : " + str(bootflash) + ' ' + "KB"
+
+
+ """
+ Input: command to check the interface status
+ e.g show interface ethernet 1/1
+ Output : parse the json output and update the html file
+ """
+ def monit(self, cmd, i, j):
+
+ out = json.loads(clid(cmd))
+
+ in_err = out['TABLE_interface']['ROW_interface']['eth_inerr']
+ out_err = out['TABLE_interface']['ROW_interface']['eth_outerr']
+ key = str(i)+"/"+str(j)
+ if (int(in_err) == 0):
+ Interface_Monit.in_err.update({key:"No"})
+ else:
+ Interface_Monit.in_err.update({key:"Yes"})
+ if (int(out_err) == 0):
+ Interface_Monit.out_err.update({key:"No"})
+ else:
+ Interface_Monit.in_err.update({key:"Yes"})
+
+
+ def interface_rx_tx(self):
+ table = "{0:16}{1:9}{2:9}{3:9}{4:9}{5:9}{6:9}{7:9}{8:9}"
+
+ out = json.loads(clid("show interface status"))
+ Interface_Monit.interface_list = out['TABLE_interface']['ROW_interface']
+
+
+ print '----------------------------------------------------------------------------------------------------------'
+ print table.format("Interface", "Rx Mbps", "Rx %", "Rx pps", "Tx Mbps", "Tx %", "Tx pps", "In Error", "Out Error")
+ print '----------------------------------------------------------------------------------------------------------'
+
+ counter = 0;
+ for i in Interface_Monit.interface_list:
+ for key,value in i.items():
+ counter = counter+1;
+ if (key == 'interface'):
+ m = re.search('Ethernet(.*)', value)
+ if m:
+ found = m.group(1)
+ slotport = found.split('/')
+
+ cmd = "show interface ethernet"+str(slotport[0])+"/"+str(slotport[1])
+ out = json.loads(clid(cmd))
+
+ bw = int(out['TABLE_interface']['ROW_interface']['eth_bw'])
+ rx_bps = int(out['TABLE_interface']['ROW_interface']['eth_inrate1_bits'])
+ rx_mbps = round((rx_bps / 1000000), 1)
+ rx_pcnt = round((rx_bps / 1000) * 100 / bw, 1)
+ rx_pps = out['TABLE_interface']['ROW_interface']['eth_inrate1_pkts']
+
+ tx_bps = int(out['TABLE_interface']['ROW_interface']['eth_outrate1_bits'])
+ tx_mbps = round((tx_bps / 1000000), 1)
+ tx_pcnt = round((tx_bps / 1000) * 100 / bw, 1)
+ tx_pps = out['TABLE_interface']['ROW_interface']['eth_outrate1_pkts']
+
+ in_err = int(out['TABLE_interface']['ROW_interface']['eth_inerr'])
+ out_err = int(out['TABLE_interface']['ROW_interface']['eth_outerr'])
+
+
+ print table.format(value, str(rx_mbps), str(rx_pcnt) + '%', rx_pps, str(tx_mbps), str(tx_pcnt) + '%', tx_pps, in_err, out_err)
+ sys.stdout.flush()
+
+
+
+
+
+
+ #create a command to get the interface status
+ def interfacemonit(self):
+ interfaceob = Interface_Monit()
+
+ for i in Interface_Monit.interface_list:
+ for key,value in i.items():
+ if (key == 'interface'):
+ m = re.search('Ethernet(.*)', value)
+ if m:
+ found = m.group(1)
+ slotport = found.split('/')
+
+ cmd = "show interface ethernet"+str(slotport[0])+"/"+str(slotport[1])
+ interfaceob.monit(cmd, slotport[0], slotport[1])
+
+
+ #interface monitoring status with details about input and output errors
+ def status(self):
+ global input_counter, output_counter, inerr_interface, outerr_interface
+ input_counter = 0; output_counter=0; inerr_interface = []; outerr_interface = [];
+
+ for key,value in Interface_Monit.in_err.items():
+ if (value == "Yes"):
+ input_counter = input_counter + 1;
+ inerr_interface.append(key)
+
+ for key,value in Interface_Monit.out_err.items():
+ if (value == "Yes"):
+ output_counter = output_counter + 1;
+ outerr_interface.append(key)
+
+
+ if (input_counter == 0):
+ print "Number of Interfaces with Input Errors is : " + ' ' + str(input_counter)
+ else:
+ print "Number of Interfaces with Input Errors is : " + ' ' + str(input_counter)
+ for key in inerr_interface:
+ print key
+
+ if (output_counter == 0):
+ print "Number of Interfaces with Output Errors is : " + ' ' + str(output_counter)
+ else:
+ print "Number of Interfaces with Output Errors is : " + ' ' + str(output_counter)
+ for key in outerr_interface:
+ print key
+
+
+
+
+if __name__ == '__main__':
+ interfaceobj = Interface_Monit()
+ interfaceobj.nexus_version()
+ interfaceobj.interface_rx_tx()
+ interfaceobj.interfacemonit()
+ interfaceobj.status()
+
+
diff --git a/nexusscripts/on-box/monitoring/systemresc_monitor.py b/nexusscripts/on-box/monitoring/systemresc_monitor.py
new file mode 100644
index 00000000..b75412fc
--- /dev/null
+++ b/nexusscripts/on-box/monitoring/systemresc_monitor.py
@@ -0,0 +1,103 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Monitoring
+:Box Type:On-Box
+:Title:System Resources Monitoring
+:Short Description:This script is to monitor system-level resources.
+:Long Description:This script is to monitor system-level resources
+like cpu utilization, memory usage etc
+:Input:command to check the system resources status
+ e.g show system resources
+:Output:parse the json output and update the html file
+"""
+
+import os,sys
+import json
+from cli import *
+
+
+"""
+class to monitor system-level resources
+cpu-utilization, memory usage
+
+"""
+class System_Monit:
+
+
+ cpu_utilization = {}
+ mem_usage = {}
+
+
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+
+ versioncmd = "show version"
+ out = json.loads(clid(versioncmd))
+ chassis_id = out['chassis_id']
+ osversion = out['rr_sys_ver']
+ cpu_name = out['cpu_name']
+ memory = out['memory']
+ processor_board = out['proc_board_id']
+ device = out['host_name']
+ bootflash = out['bootflash_size']
+
+ print "Nexus Switch OS version is :" , osversion
+ print "Chassis ID is :", chassis_id
+ print cpu_name + ' ' + "with" + ' ' + str(memory) + ' ' + "KB of memory"
+ print "Processor Board ID is " + processor_board
+
+ print "Host Name : " + device
+ print "Bootflash : " + str(bootflash) + ' ' + "KB"
+
+
+ #get the monitoring data from the nexus switch
+ def monit_data(self):
+
+ out = json.loads(clid("show system resources"))
+ self.cpu_kernel = out['cpu_state_kernel']
+ self.cpu_idle = out['cpu_state_idle']
+ self.cpu_user = out['cpu_state_user']
+
+ #update the cpu_utilization dictionary
+ System_Monit.cpu_utilization.update({'Cpu_state_kernel':self.cpu_kernel})
+ System_Monit.cpu_utilization.update({'Cpu_state_idle':self.cpu_idle})
+ System_Monit.cpu_utilization.update({'Cpu_state_user':self.cpu_user})
+
+
+ self.mem_used = out['memory_usage_used']
+ self.mem_free = out['memory_usage_free']
+ self.mem_total = out['memory_usage_total']
+ self.mem_status = out['current_memory_status']
+
+ #update the memory usage dictionary
+ System_Monit.mem_usage.update({'Memory_Usage_Used':self.mem_used})
+ System_Monit.mem_usage.update({'Memory_Usage_Free':self.mem_free})
+ System_Monit.mem_usage.update({'Memory_Usage_Total':self.mem_total})
+ System_Monit.mem_usage.update({'Current_Memory_Status':self.mem_status})
+
+ #overall cpu utilization and memory usage in percentage
+ def status(self):
+ global cpu_percent,mem_percent
+ total_cpu = float(System_Monit.cpu_utilization['Cpu_state_kernel']) + float(System_Monit.cpu_utilization['Cpu_state_user'])
+ cpu_percent = (total_cpu)/2
+ print "Overall CPU Utilization is : " + str(cpu_percent) + "%"
+
+
+ mem_used = float(System_Monit.mem_usage['Memory_Usage_Used']) / float(System_Monit.mem_usage['Memory_Usage_Total'])
+
+ memory_per = mem_used*100
+ mem_percent = round(memory_per,2)
+
+ print "Overall Memory Usage (%) : " + str(mem_percent) + "%"
+ print "Overall Memory Usage (Bytes) : " + str(System_Monit.mem_usage['Memory_Usage_Used']) + \
+ ' ' + "Used " + "," + ' ' + str(System_Monit.mem_usage['Memory_Usage_Free']) + ' ' + "Free " + "," + str(System_Monit.mem_usage['Memory_Usage_Total']) + \
+ ' ' + "Total"
+
+
+if __name__ == '__main__':
+ systemob = System_Monit()
+ systemob.nexus_version()
+ systemob.monit_data()
+ systemob.status()
+
diff --git a/nexusscripts/on-box/troubleshoot/README.md b/nexusscripts/on-box/troubleshoot/README.md
new file mode 100644
index 00000000..bb3a5d3f
--- /dev/null
+++ b/nexusscripts/on-box/troubleshoot/README.md
@@ -0,0 +1,17 @@
+#Nexus 9000 Switch Automation tasks
+
+#Automation of Switch Trouble shooting Category
+Python version > 2.7.*
+
+Nexus Switch version is NXOS: version 6.1(2)I3(1)
+
+
+1. Trouble shoot FEX
+
+ Steps :
+
+ a. execute the script (fex_troubleshoot.py) to check the FEX configuration along with interfaces associated with FEX.
+ b. command to execute: "python filename"
+
+
+
diff --git a/nexusscripts/on-box/troubleshoot/fex_troubleshoot.py b/nexusscripts/on-box/troubleshoot/fex_troubleshoot.py
new file mode 100644
index 00000000..9b0adf0f
--- /dev/null
+++ b/nexusscripts/on-box/troubleshoot/fex_troubleshoot.py
@@ -0,0 +1,93 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Troubleshooting
+:Box Type:On-Box
+:Title:FEX issues
+:Short Description:To identify FEX issues
+:Long Description:Check the FEX state
+installed/enabled etc
+:Input:command to check the FEX installation,
+associated interfaces etc
+:Output:FEX status
+"""
+
+import os,sys
+import json
+import ConfigParser
+from cli import *
+
+
+"""
+
+Class to troubleshoot FEX on the Nexus Switch
+"""
+
+class FEX_Troubleshoot:
+
+ stat = '';
+
+ #get the nexus switch version and chassis details
+ def nexus_version(self):
+ global osversion;
+ versioncmd = "show version"
+ out = json.loads(clid(versioncmd))
+ chassis_id = out['chassis_id']
+ osversion = out['rr_sys_ver']
+ cpu_name = out['cpu_name']
+ memory = out['memory']
+ processor_board = out['proc_board_id']
+ device = out['host_name']
+ bootflash = out['bootflash_size']
+
+ print "Nexus Switch OS version is :" , osversion
+ print "Chassis ID is :", chassis_id
+ print cpu_name + ' ' + "with" + ' ' + str(memory) + ' ' + "KB of memory"
+ print "Processor Board ID is " + processor_board
+
+ print "Host Name : " + device
+ print "Bootflash : " + str(bootflash) + ' ' + "KB"
+
+
+ def fex_status(self):
+
+ out = json.loads(clid("show feature-set fex"))
+ status = out['TABLE-cfcFeatureSetTable']['cfcFeatureSetOpStatus']
+ FEX_Troubleshoot.stat = "On " + osversion + " Nexus Switch FEX is " + status
+ print FEX_Troubleshoot.stat
+
+ def fex_interfaces(self):
+
+ try:
+ out = json.loads(clid("show interface fex-fabric"))
+ #print out
+ status = out['TABLE_fex_fabric']['ROW_fex_fabric']
+ FEX_Troubleshoot.stat = "On " + osversion + " Nexus Switch interfaces have detected a Fabric Extender uplink"
+ print FEX_Troubleshoot.stat
+ print "Interfaces configured are:"
+
+ if (isinstance(status, list)):
+ for i in status:
+ for key,value in i.items():
+ if (key == 'fbr_port'):
+ print value
+ elif (isinstance(status, dict)):
+ for key,value in status.items():
+ if (key == 'fbr_port'):
+ print value
+ else:
+ print "Not implemented for this response type"
+
+ except:
+ FEX_Troubleshoot.stat = "On " + osversion + " Nexus Switch interfaces are not configured to FEX uplink"
+ print FEX_Troubleshoot.stat
+
+ #status = out['TABLE_fex_fabric']['ROW_fex_fabric']
+ #print status
+
+
+if __name__ == '__main__':
+ systemob = FEX_Troubleshoot()
+ systemob.nexus_version()
+ systemob.fex_status()
+ systemob.fex_interfaces()
+
diff --git a/nexusscripts/on-box/upgrade_patch_mgmt/patch_mgmt.py b/nexusscripts/on-box/upgrade_patch_mgmt/patch_mgmt.py
new file mode 100644
index 00000000..10ab1e45
--- /dev/null
+++ b/nexusscripts/on-box/upgrade_patch_mgmt/patch_mgmt.py
@@ -0,0 +1,263 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:OS-Mgmt
+:Box Type:On-Box
+:Title:Patch Management
+:Short Description:This script is to perform patch related operations
+:Long Description:This script is to perform operations like
+ copyactivatedeactivateremove patch files.
+:Input:tftp_addresssmu_fileaction
+:Output:status/result of the patch management action
+"""
+
+"""Examples
+
+(1) install activate
+(2) install commit (active)
+(3) install deactivate
+(4) install commit (inactive)
+(5) install remove
+
+(1) install activate
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action activate
+install add bootflash:n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 179 completed successfully at Tue Jan 27 09:13:02 2015
+show install inactive
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+install activate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 180 completed successfully at Tue Jan 27 09:13:08 2015
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Tue Jan 27 09:13:08 2015
+Install operation 180 by user admin at Tue Jan 27 09:13:02 2015
+Install activate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 180 completed successfully at Tue Jan 27 09:13:08 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Committed Packages:
+Tue Jan 27 09:13:39 2015
+Install operation 180 by user admin at Tue Jan 27 09:13:02 2015
+Install activate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 180 completed successfully at Tue Jan 27 09:13:08 2015
+
+(2) install commit (active)
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --use r admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action commit_active
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 181 completed successfully at Tue Jan 27 09:14:09 2015
+Tue Jan 27 09:14:09 2015
+Install operation 181 by user admin at Tue Jan 27 09:14:07 2015
+Install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 181 completed successfully at Tue Jan 27 09:14:09 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --use r admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Committed Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Tue Jan 27 09:14:17 2015
+Install operation 181 by user admin at Tue Jan 27 09:14:07 2015
+Install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 181 completed successfully at Tue Jan 27 09:14:09 2015
+
+(3) install deactivate
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action deactivate
+Active Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+install deactivate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 182 completed successfully at Tue Jan 27 09:15:10 2015
+show install inactive
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Tue Jan 27 09:15:10 2015
+Install operation 182 by user admin at Tue Jan 27 09:15:04 2015
+Install deactivate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 182 completed successfully at Tue Jan 27 09:15:10 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Active Packages:
+Committed Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Tue Jan 27 09:15:18 2015
+Install operation 182 by user admin at Tue Jan 27 09:15:04 2015
+Install deactivate n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 182 completed successfully at Tue Jan 27 09:15:10 2015
+
+(4) install commit (inactive)
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action commit_inactive
+show install inactive
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 184 completed successfully at Tue Jan 27 09:16:03 2015
+Tue Jan 27 09:16:03 2015
+Install operation 184 by user admin at Tue Jan 27 09:16:01 2015
+Install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 184 completed successfully at Tue Jan 27 09:16:03 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Active Packages:
+Committed Packages:
+Tue Jan 27 09:16:10 2015
+Install operation 184 by user admin at Tue Jan 27 09:16:01 2015
+Install commit n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 184 completed successfully at Tue Jan 27 09:16:03 2015
+
+(5) install remove
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action remove
+show install inactive
+Inactive Packages:
+ n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 185 completed successfully at Tue Jan 27 09:16:46 2015
+Tue Jan 27 09:16:46 2015
+Install operation 185 by user admin at Tue Jan 27 09:16:46 2015
+Install remove n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 185 completed successfully at Tue Jan 27 09:16:46 2015
+
+root@aio178:/home/localadmin/nexus9000/nexusscripts/off-box/upgrade_patch_mgmt# python patch_mgmt.py --n9k 10.1.150.11 --user admin --password \!cisco123 --smu_filename n9000-dk9.6.1.2.I3.1.CSCur02700.bin --action status
+Inactive Packages:
+Active Packages:
+Committed Packages:
+Tue Jan 27 09:16:50 2015
+Install operation 185 by user admin at Tue Jan 27 09:16:46 2015
+Install remove n9000-dk9.6.1.2.I3.1.CSCur02700.bin
+Install operation 185 completed successfully at Tue Jan 27 09:16:46 2015
+
+End of Examples
+"""
+
+
+import argparse
+import sys
+from cli import *
+
+
+class Args(object):
+ def __init__(self, args):
+ self.tftp_address = args.tftp_address
+ self.smu_filename = args.smu_filename
+ self.action = args.action
+
+def exe_cmd(cmd_str):
+ print cmd_str
+ return_xml = clip(cmd_str)
+ print return_xml
+
+def copy_patch_file(params):
+
+ cmd_str = 'copy tftp://'
+ cmd_str += params.tftp_address
+ cmd_str += '/'
+ cmd_str += params.smu_filename
+ cmd_str += ' bootflash:// vrf management'
+ exe_cmd(cmd_str)
+
+def list_patch_file(params):
+ cmd_str = 'dir bootflash:'
+ cmd_str += params.smu_filename
+ exe_cmd(cmd_str)
+
+def add_module(params):
+ cmd_str = 'install add bootflash:'
+ cmd_str += params.smu_filename
+ exe_cmd(cmd_str)
+
+def list_inactive_modules():
+ cmd_str = 'show install inactive'
+ exe_cmd(cmd_str)
+
+def activate_patch_file(params):
+ cmd_str = 'install activate '
+ cmd_str += params.smu_filename
+ exe_cmd(cmd_str)
+
+def commit_active_patch_file(params):
+ cmd_str = 'install commit '
+ cmd_str += params.smu_filename
+ exe_cmd(cmd_str)
+
+def commit_inactive_patch_file(params):
+ cmd_str = 'install commit '
+ cmd_str += params.smu_filename
+ exe_cmd(cmd_str)
+
+def list_modules_status():
+# print 'show install inactive'
+ exe_cmd('show install inactive')
+
+# print 'show install active'
+ exe_cmd('show install active')
+
+# print 'show install committed'
+ exe_cmd('show install committed')
+
+def list_active_modules():
+ exe_cmd('show install active')
+
+def deactivate_patch_file(params):
+ exe_cmd('install deactivate ' + params.smu_filename)
+
+def remove_modules(params):
+ exe_cmd('install remove ' + params.smu_filename + ' forced')
+
+def show_install_log():
+ exe_cmd('show install log last')
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 OS software patch management utility.',
+ epilog="""to openstack cluster.""")
+
+ parser.add_argument('--tftp_address', '-a', dest='tftp_address',
+ help='Tftp server ip-address.')
+ parser.add_argument('--smu_filename', '-f', dest='smu_filename',
+ help='SMU filename.', required=True)
+ parser.add_argument('--action''-o', dest='action',
+ help='Action Install/Remove patch file.', required=True,
+ choices = ['copy', 'activate', 'deactivate', 'commit_active', 'commit_inactive', 'remove''status'])
+ args = parser.parse_args()
+ return Args(args)
+
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+
+ if params.action == 'copy':
+ if not params.tftp_address:
+ params.tftp_address = raw_input('tftp server address:')
+ copy_patch_file(params)
+ list_patch_file(params)
+ elif params.action == 'activate':
+ add_module(params)
+ list_inactive_modules()
+ activate_patch_file(params)
+ list_active_modules()
+ elif params.action == 'deactivate':
+ list_active_modules()
+ deactivate_patch_file(params)
+ list_inactive_modules()
+ elif params.action == 'remove':
+ list_inactive_modules()
+ remove_modules(params)
+ elif params.action == 'commit_active':
+ list_active_modules()
+ commit_active_patch_file(params)
+ elif params.action == 'commit_inactive':
+ list_inactive_modules()
+ commit_inactive_patch_file(params)
+ elif params.action == 'status':
+ list_modules_status()
+ show_install_log()
+ exit(0)
diff --git a/nexusscripts/on-box/upgrade_patch_mgmt/sw_mgmt.py b/nexusscripts/on-box/upgrade_patch_mgmt/sw_mgmt.py
new file mode 100644
index 00000000..93a906c1
--- /dev/null
+++ b/nexusscripts/on-box/upgrade_patch_mgmt/sw_mgmt.py
@@ -0,0 +1,110 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:OS-Mgmt
+:Box Type:On-Box
+:Title:Software Management
+:Short Description:This script is to perform Software management operations
+:Long Description:This script is to perform operations like
+ copy, upgrade, downgrade, remove switch images.
+:Input:N9K Address, username, password, tftp_address, image_filename, action
+:Output:status/result of the software management action
+"""
+
+import argparse
+from cli import *
+import sys
+
+class Args(object):
+
+ def __init__(self, args):
+ self.tftp_address = args.tftp_address
+ self.image_filename = args.image_filename
+ self.action = args.action
+
+
+def copy_image_file(params):
+
+ print 'copy tftp://'+ params.tftp_address + '/' + params.image_filename +\
+ ' bootflash:// vrf management'
+ return_xml = cli('copy tftp://'+ params.tftp_address + '/' +\
+ params.image_filename + ' bootflash:// vrf management')
+ print return_xml
+
+
+def verify_active_sessions():
+ print 'show configuration session summary'
+ return_xml = cli('show configuration session summary')
+ print return_xml
+
+
+def check_image_incompatibility(params):
+ print 'show incompatibility nxos bootflash:' +\
+ params.image_filename
+ return_xml = cli('show incompatibility nxos bootflash:' +\
+ params.image_filename)
+ print return_xml
+
+
+def remove_image(params):
+ print 'delete bootflash:' + params.image_filename + " no-prompt"
+ return_xml = cli('delete bootflash:' +\
+ params.image_filename + " no-prompt")
+ print return_xml
+
+
+def check_install_all_impact(params):
+ print 'show install all impact nxos bootflash:' +\
+ params.image_filename
+ return_data = cli('show install all impact nxos bootflash:' +\
+ params.image_filename)
+ print return_data
+
+
+def copy_run_cfg_start_cfg():
+ print 'copy running-config startup-config'
+ return_data = cli('copy running-config startup-config')
+ print return_data
+
+
+def install_all_nxos_image(params):
+ print 'install all parallel nxos bootflash:' +\
+ params.image_filename
+ return_data = cli('install all parallel nxos bootflash:' +\
+ params.image_filename)
+ print return_data
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 OS software patch management utility.',
+ epilog=""" """)
+
+ parser.add_argument('--tftp-address', '-a', dest='tftp_address',
+ help='Tftp server ip-address.')
+ parser.add_argument('--image_filename', '-f', dest='image_filename',
+ help='Image filename.', required=True)
+ parser.add_argument('--action', '-o', dest='action',
+ help='Action Upgrade/Downgrade switch image.',
+ required=True, choices = ['copy', 'upgrade', 'downgrade', 'remove'])
+ args = parser.parse_args()
+ return Args(args)
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+
+ if params.action == 'copy':
+ copy_image_file(params)
+ elif params.action == 'upgrade':
+ verify_active_sessions()
+ elif params.action == 'downgrade':
+ check_image_incompatibility(params)
+ elif params.action == 'remove':
+ remove_image(params)
+
+ if params.action in {'upgrade','downgrade'}:
+ check_install_all_impact(params)
+ copy_run_cfg_start_cfg()
+ install_all_nxos_image(params)
+ exit(0)
diff --git a/nexusscripts/sample_script.py b/nexusscripts/sample_script.py
new file mode 100644
index 00000000..1fe954ad
--- /dev/null
+++ b/nexusscripts/sample_script.py
@@ -0,0 +1,22 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:Monitoring
+:Title:Interface Monitoring
+:Short Description:This script is to monitor Interface counters.
+:Long Description:This script is to monitor Interface counters like
+Drops, Errors, Utilization.
+:Input:Interface ID
+:Output:Drop, Errors and Utilization Status.
+"""
+
+import os
+
+def main():
+ """
+ This method will do the monitoring functionality
+ """
+ print "Printing Sample Status"
+
+
+if __name__ == '__main__':
+ main()
diff --git a/nexusscripts/upgrade_patch_mgmt/patch_mgmt.py b/nexusscripts/upgrade_patch_mgmt/patch_mgmt.py
new file mode 100644
index 00000000..aa7c9d65
--- /dev/null
+++ b/nexusscripts/upgrade_patch_mgmt/patch_mgmt.py
@@ -0,0 +1,201 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:OS Software Patch Management
+:Title:Patch Management
+:Short Description:This script is to perform patch related operations
+:Long Description:This script is to perform operations like
+ copy, activate, deactivate, remove patch files.
+:Input: N9K Address, username, password, tftp_address, smu_file, action
+:Output:status/result of the patch management action
+"""
+
+import argparse
+import getpass
+import sys
+
+sys.path.append("../../nx-os/nxapi/utils")
+
+from nxapi_utils import NXAPI
+import xmltodict
+
+
+class Args(object):
+ def __init__(self, args):
+ self.n9k = args.hostname
+ self.username = args.username
+ self.password = args.password
+ if not self.password:
+ self.password = getpass.getpass()
+ self.tftp_address = args.tftp_address
+ self.smu_filename = args.smu_filename
+ self.action = args.action
+
+
+def initialize_nxapi_handler(params):
+ nxapi = NXAPI()
+ nxapi.set_target_url('http://' + params.n9k + '/ins')
+ nxapi.set_username(params.username)
+ nxapi.set_password(params.password)
+ nxapi.set_msg_type('cli_conf')
+ return nxapi
+
+
+def check_status(dict_res):
+ if dict_res['ins_api']['outputs']['output']['code'] == '200' and \
+ dict_res['ins_api']['outputs']['output']['msg'] == 'Success':
+ print dict_res['ins_api']['outputs']['output']['body']
+ return True
+ else:
+ print 'Error Msg:' + dict_res['ins_api']['outputs']['output']['msg']
+ print 'Code:' + dict_res['ins_api']['outputs']['output']['code']
+ return False
+
+
+def copy_patch_file(params, nxapi_handler):
+ print 'copy tftp://'+ params.tftp_address + '/' + params.smu_filename +\
+ ' bootflash:// vrf management'
+ nxapi_handler.set_cmd('copy tftp://'+ params.tftp_address + '/' +
+ params.smu_filename + ' bootflash:// vrf management')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def list_patch_file(params, nxapi_handler):
+ print 'dir bootflash:' + params.smu_filename
+ nxapi_handler.set_cmd('dir bootflash:' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def add_module(params, nxapi_handler):
+ print 'install add bootflash:' + params.smu_filename
+ nxapi_handler.set_cmd('install add bootflash:' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def list_inactive_modules(nxapi_handler):
+ print 'show install inactive'
+ nxapi_handler.set_cmd('show install inactive')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def activate_patch_file(params, nxapi_handler):
+ print 'install activate ' + params.smu_filename
+ nxapi_handler.set_cmd('install activate ' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def list_active_modules(nxapi_handler):
+ nxapi_handler.set_cmd('show install active')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def deactivate_patch_file(params, nxapi_handler):
+ print 'install deactivate ' + params.smu_filename
+ nxapi_handler.set_cmd('install deactivate ' + params.smu_filename)
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def remove_modules(params, nxapi_handler):
+ nxapi_handler.set_cmd('install remove ' + params.smu_filename + ' forced')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def show_install_log(nxapi_handler):
+ nxapi_handler.set_cmd('show install log detail')
+ returnData = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(returnData[1])
+ return check_status(dict_res)
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 OS software patch management utility.',
+ epilog="""to openstack cluster.""")
+
+ parser.add_argument('--n9k', '-i', dest='hostname',
+ help='Nexus 9XXX hostname or ip address', required=True)
+ parser.add_argument('--user', '-u', dest='username',
+ help='Username to login to Nexus 9XXX switch', required=True)
+ parser.add_argument('--password', '-p', dest='password',
+ help='Password to login to Nexus 9XXX switch')
+ parser.add_argument('--tftp_address', '-a', dest='tftp_address',
+ help='Tftp server ip-address.')
+ parser.add_argument('--smu_filename', '-f', dest='smu_filename',
+ help='SMU filename.', required=True)
+ parser.add_argument('--action', '-o', dest='action',
+ help='Action Install/Remove patch file.', required=True,
+ choices = ['copy', 'activate', 'deactivate', 'remove'])
+ args = parser.parse_args()
+ return Args(args)
+
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+
+ nxapi_handler = initialize_nxapi_handler(params)
+
+ if params.action == 'copy':
+ if not params.tftp_address:
+ params.tftp_address = raw_input('tftp server address:')
+ if not copy_patch_file(params, nxapi_handler):
+ print 'Failed to copy patch file'
+ if not list_patch_file(params, nxapi_handler):
+ print 'Failed to copy patch file'
+ else:
+ print 'Patch file:' + params.smu_filename + ' already present'
+ exit(-1)
+ if not list_patch_file(params, nxapi_handler):
+ print 'Failed to copy patch file'
+ exit(-1)
+ elif params.action == 'activate':
+ if not add_module(params, nxapi_handler):
+ print 'Failed to activate module.'
+ exit(-1)
+ if not list_inactive_modules(nxapi_handler):
+ print 'Failed to list inactive modules.'
+ exit(-1)
+ if not activate_patch_file(params, nxapi_handler):
+ print 'Failed to activate patch file.'
+ exit(-1)
+ if not list_active_modules(nxapi_handler):
+ print 'Failed to list active modules'
+ exit(-1)
+ elif params.action == 'deactivate':
+ if not list_active_modules(nxapi_handler):
+ print 'Failed to list active modules'
+ exit(-1)
+ if not deactivate_patch_file(params, nxapi_handler):
+ print 'Failed to deactivate patch file.'
+ exit(-1)
+ if not list_inactive_modules(nxapi_handler):
+ print 'Failed to list inactive modules.'
+ exit(-1)
+ elif params.action == 'remove':
+ if not list_inactive_modules(nxapi_handler):
+ print 'Failed to list inactive modules.'
+ exit(-1)
+ if not remove_modules(params, nxapi_handler):
+ print 'Failed to remove module.'
+ exit(-1)
+
+ if not show_install_log(nxap_handleri):
+ print 'Failed to get install log.'
+ exit(-1)
+ exit(0)
diff --git a/nexusscripts/upgrade_patch_mgmt/sw_mgmt.py b/nexusscripts/upgrade_patch_mgmt/sw_mgmt.py
new file mode 100644
index 00000000..c1af9614
--- /dev/null
+++ b/nexusscripts/upgrade_patch_mgmt/sw_mgmt.py
@@ -0,0 +1,166 @@
+"""Script Cataloging Information
+:Product Info:Nexus::9000::9516::NX-OS Release 6.2
+:Category:OS Software Upgrade Management
+:Title: Software Management
+:Short Description:This script is to perform Software management operations
+:Long Description:This script is to perform operations like
+ copy, upgrade, downgrade, remove switch images.
+:Input: N9K Address, username, password, tftp_address, image_filename, action
+:Output:status/result of the software management action
+"""
+
+import argparse
+import getpass
+import sys
+
+sys.path.append("../../nx-os/nxapi/utils")
+from nxapi_utils import *
+from xmltodict import *
+
+
+class Args(object):
+
+ def __init__(self, args):
+ self.n9k = args.hostname
+ self.username = args.username
+ self.password = args.password
+ if not self.password:
+ self.password = getpass.getpass()
+ self.tftp_address = args.tftp_address
+ self.timeout = args.timeout
+ self.image_filename = args.image_filename
+ self.action = args.action
+
+
+def initialize_nxapi_handler(params):
+
+ thisNXAPI = NXAPI()
+ thisNXAPI.set_target_url('http://' + params.n9k +'/ins')
+ thisNXAPI.set_username(params.username)
+ thisNXAPI.set_password(params.password)
+ thisNXAPI.set_timeout(params.timeout)
+ thisNXAPI.set_msg_type('cli_conf')
+ return thisNXAPI
+
+
+def check_status(dict_res):
+
+ if dict_res['ins_api']['outputs']['output']['code'] == '200' and \
+ dict_res['ins_api']['outputs']['output']['msg'] == 'Success':
+ print dict_res['ins_api']['outputs']['output']['body']
+ return True
+ else:
+ print 'Error Msg:' + dict_res['ins_api']['outputs']['output']['msg']
+ print 'Code:' + dict_res['ins_api']['outputs']['output']['code']
+ return False
+
+
+def copy_image_file(params, nxapi_handler):
+
+ print 'copy tftp://'+ params.tftp_address + '/' + params.image_filename +\
+ ' bootflash:// vrf management'
+ nxapi_handler.set_cmd('copy tftp://'+ params.tftp_address + '/' +\
+ params.image_filename + ' bootflash:// vrf management')
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def verify_active_sessions(nxapi_handler):
+ print 'show configuration session summary'
+ nxapi_handler.set_cmd('show configuration session summary')
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def check_image_incompatability(params, nxapi_handler):
+ nxapi_handler.set_cmd('show incompatability nxos bootflash:' +\
+ params.image_filename)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def check_install_all_impact(params, nxapi_handler):
+ print 'show install all impact nxos bootflash:' +\
+ params.image_filename
+ nxapi_handler.set_cmd('show install all impact nxos bootflash:' +\
+ params.image_filename)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def copy_run_cfg_start_cfg(nxapi_handler):
+ print 'copy running-config startup-config'
+ nxapi_handler.set_cmd('copy running-config startup-config')
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def install_all_nxos_image(params, nxapi_handler):
+ print 'install all parallel nxos bootflash:' +\
+ params.image_filename
+ nxapi_handler.set_cmd('install all parallel nxos bootflash:' +\
+ params.image_filename)
+ return_xml = nxapi_handler.send_req()
+ dict_res = xmltodict.parse(return_xml[1])
+ return check_status(dict_res)
+
+
+def initialize_args():
+
+ parser = argparse.ArgumentParser(
+ description='Nexus 9000 OS software patch management utility.',
+ epilog=""" """)
+
+ parser.add_argument('--n9k', '-i', dest='hostname',
+ help='Nexus 9XXX hostname or ip address', required=True)
+ parser.add_argument('--user', '-u', dest='username',
+ help='Username to login to Nexus 9XXX switch', required=True)
+ parser.add_argument('--password', '-p', dest='password',
+ help='Password to login to Nexus 9XXX switch')
+ parser.add_argument('--tftp-address', '-a', dest='tftp_address',
+ help='Tftp server ip-address.')
+ parser.add_argument('--image_filename', '-f', dest='image_filename',
+ help='Image filename.', required=True)
+ parser.add_argument('--timeout', '-t', dest='timeout',
+ help='Connection Timeout.', default=600)
+ parser.add_argument('--action', '-o', dest='action',
+ help='Action Upgrade/Downgrade switch image.',
+ required=True, choices = ['copy', 'upgrade', 'downgrade', 'remove'])
+ args = parser.parse_args()
+ return Args(args)
+
+if __name__ == '__main__':
+
+ params = initialize_args()
+ nxapi_handler = initialize_nxapi_handler(params)
+
+ if params.action == 'copy':
+ if not copy_image_file(params, nxapi_handler):
+ print 'Failed to copy image file'
+ exit(-1)
+ elif params.action == 'upgrade':
+ # pre-requisite check before upgrading
+ if not verify_active_sessions(nxapi_handler):
+ print 'Failed to verify active sessions'
+ exit(-1)
+ elif params.action == 'downgrade':
+ if not check_image_incompatability(params, nxapi_handler):
+ print 'Failed to check image incompatability'
+ exit(-1)
+
+ if params.action in {'upgrade','downgrade'}:
+ if not check_install_all_impact(params, nxapi_handler):
+ print 'Failed to check install all impact.'
+ exit(-1)
+ if not copy_run_cfg_start_cfg(nxapi_handler):
+ print 'Failed to copy running-config to startup-config.'
+ exit(-1)
+ if not install_all_nxos_image(params, nxapi_handler):
+ print 'Failed to update switch image file.'
+ exit(-1)
+ exit(0)