本文整理汇总了Python中device.Device.show方法的典型用法代码示例。如果您正苦于以下问题:Python Device.show方法的具体用法?Python Device.show怎么用?Python Device.show使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类device.Device
的用法示例。
在下文中一共展示了Device.show方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: show_run
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def show_run(switch_ip, intf_id):
switch_user = 'admin'
switch_pw = 'cisco123'
switch = Device(ip=switch_ip, username=switch_user, password=switch_pw)
switch.open()
command = switch.show('show interface ' + intf_id + ' switchport')
show_dict = xmltodict.parse(command[1])
results = show_dict['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']
oper_mode = results['oper_mode']
access_vlan = results['access_vlan']
command = switch.show('show interface ' + intf_id)
show_dict = xmltodict.parse(command[1])
results = show_dict['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']
desc = results['desc']
config_text = 'interface ' + intf_id + '\n description ' + desc + '\n switchport mode ' + oper_mode + '\n switchport access vlan ' + access_vlan + '\n!\n'
return config_text
示例2: show_run
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def show_run(switch_ip, intf_id):
"""
This accepts the switch info and and interface.
params:
switch_ip (string): ip address of switch
intf_id (string): interface to check config
"""
switch_user = "admin"
switch_pw = "cisco123"
# Connect to switch
switch = Device(ip=switch_ip, username=switch_user, password=switch_pw)
switch.open()
# Parse VLAN data into dictionary
command = switch.show("show interface " + intf_id + " switchport")
show_dict = xmltodict.parse(command[1])
results = show_dict["ins_api"]["outputs"]["output"]["body"]["TABLE_interface"]["ROW_interface"]
oper_mode = results["oper_mode"]
access_vlan = results["access_vlan"]
# Parse description data into dictionary
command = switch.show("show interface " + intf_id)
show_dict = xmltodict.parse(command[1])
results = show_dict["ins_api"]["outputs"]["output"]["body"]["TABLE_interface"]["ROW_interface"]
if "desc" in results:
desc = "description " + results["desc"]
else:
desc = "no description"
# Create NXOS formatted text to return
config_text = (
"interface "
+ intf_id
+ "\n "
+ desc
+ "\n switchport mode "
+ oper_mode
+ "\n switchport access vlan "
+ access_vlan
+ "\n!\n"
)
return config_text
示例3: getswitchinfo
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def getswitchinfo(sw):
switch = Device(ip=sw)
switch.open()
getdata = switch.show('show interface brief')
show_intf_dict = xmltodict.parse(getdata[1])
data = show_intf_dict['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']
#rint data
# Code to loop through interfaces and put all 'up' in a list (align list with key)
up_list= []
for each in data:
if 'up' in each.values():
up_list.append(each['interface'])
#print up_list
return up_list
示例4: get_intfs
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def get_intfs(switch_ip):
'''
This connects to the chosen switch and gets all of the ports. and vlans.
This is filtered to access ports only.
'''
switch_user = 'admin'
switch_pw = 'cisco123'
switch = Device(ip=switch_ip, username=switch_user, password=switch_pw)
switch.open()
command = switch.show('show interface')
show_dict = xmltodict.parse(command[1])
results = show_dict['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']
intf_list = []
for result in results:
if 'eth_mode' in result and result['eth_mode'] == 'access':
intf_list.append(result['interface'])
return intf_list
示例5: get_intfs
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def get_intfs(switch_ip):
"""
This connects to the chosen switch and gets all of the ports. and vlans.
This is filtered to access ports only.
"""
switch_user = "admin"
switch_pw = "cisco123"
switch = Device(ip=switch_ip, username=switch_user, password=switch_pw)
switch.open()
command = switch.show("show interface")
show_dict = xmltodict.parse(command[1])
results = show_dict["ins_api"]["outputs"]["output"]["body"]["TABLE_interface"]["ROW_interface"]
intf_list = []
for result in results:
if "eth_mode" in result and result["eth_mode"] == "access":
intf_list.append(result["interface"])
return intf_list
示例6: get_vlans
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def get_vlans(switch_ip):
'''
This connects to the chosen switch and gets all of the ports. and vlans.
This is filtered to access ports only.
'''
switch_user = 'admin'
switch_pw = 'cisco123'
switch = Device(ip=switch_ip, username=switch_user, password=switch_pw)
switch.open()
command = switch.show('show vlan')
show_dict = xmltodict.parse(command[1])
results = show_dict['ins_api']['outputs']['output']['body']['TABLE_vlanbrief']['ROW_vlanbrief']
vlan_list = []
for result in results:
if 'USER' in result['vlanshowbr-vlanname']:
vlan_list.append([result['vlanshowbr-vlanid-utf'], result['vlanshowbr-vlanname']])
# print json.dumps(show_dict, indent=4)
return vlan_list
示例7: get_switch
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def get_switch(crawler, f):
'''Open the switch, grab the hostname, and run show_lldp_neigh'''
try:
switch = Device(ip=crawler.current_address, username=crawler.username,
password=crawler.password)
switch.open()
print crawler.current_address
xmlHostname = switch.show('show hostname')
dictHostname = xmltodict.parse(xmlHostname[1])
crawler.update_hostname(dictHostname['ins_api']['outputs']['output']['body']['hostname'])
show_lldp_neigh(switch, crawler, f)
return False
except Exception, e:
print "Could not connect using NXAPI, trying a screenscrape..."
error_flag = screen_scrape(crawler, f)
return error_flag
示例8: get_vlans
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def get_vlans(switch_ip):
"""
This connects to the chosen switch and gets all of the ports. and vlans.
This is filtered to access ports only.
"""
switch_user = "admin"
switch_pw = "cisco123"
# Connect to switch
switch = Device(ip=switch_ip, username=switch_user, password=switch_pw)
switch.open()
# Parse data into dictionary
command = switch.show("show vlan")
show_dict = xmltodict.parse(command[1])
results = show_dict["ins_api"]["outputs"]["output"]["body"]["TABLE_vlanbrief"]["ROW_vlanbrief"]
vlan_list = []
for result in results:
if "USER" in result["vlanshowbr-vlanname"]:
vlan_list.append([result["vlanshowbr-vlanid-utf"], result["vlanshowbr-vlanname"]])
# print json.dumps(show_dict, indent=4)
return vlan_list
示例9: show_version
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def show_version():
'''
:return: returns the version from the json return from a switch using provided nxapi modules.
'''
args = getargs()
username = args.user
if not username:
username = raw_input("Username: ")
password = getpass.getpass("Password: ")
sw1 = Device(ip=args.ip, username=username, password=password)
sw1.open()
getversion = sw1.show('show version')
result = xmltodict.parse(getversion[1])
data = result['ins_api']['outputs']['output']['body']['kickstart_ver_str']
return data
示例10: open
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
app_file_name = file_list[1] #Approved version check file must come first after verchk.py
ip_file_name = file_list[2] #IP Address List file must come after approved version.
file_object = open(app_file_name,"r")
app_version = file_object.readline().strip()
print "\nThis is the approved version: ",app_version,"\n\tSwitches not running this version will require an upgrade"
ip_file_object = open(ip_file_name,"r")
ip_addresses = ip_file_object.readline().strip()
ip_address_list = ip_addresses.split(',')
for each_ip in ip_address_list:
switch = Device(ip=each_ip,username='admin',password='cisco123')
switch.open()
shver_command_out = switch.show('show version')
result = xmltodict.parse(shver_command_out[1])
sw_version = result['ins_api']['outputs']['output']['body']['kickstart_ver_str']
sw_hostname = result['ins_api']['outputs']['output']['body']['host_name']
sw_chassis = result['ins_api']['outputs']['output']['body']['chassis_id']
sw_chassis_list = sw_chassis.split(' ')
sw_model = sw_chassis_list[1]
print "=" * 75
print "\n\tHostname:",sw_hostname,"\n\tIP Address:",each_ip
print "\tSwitch Model: ",sw_model
if sw_version == app_version:
print "\tNo upgrade required"
示例11: Device
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
from device import Device
sw1 = Device(ip='172.31.217.138', username='admin', password='cisco123')
sw1.open()
command = sw1.show('show int e1/48')
print command
import xmltodict
import json
command = sw1.show('sh int e1/48')
result = xmltodict.parse(command[1])
print json.dumps( result, indent=4)
ip = result['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']['eth_ip_addr']
print ip
mask = result['ins_api']['outputs']['output']['body']['TABLE_interface']['ROW_interface']['eth_ip_mask']
print mask
print ip + '/' + mask
sh_vlan = sw1.show('sh vl')
sh_vlan_dict = xmltodict.parse(sh_vlan[1])
print json.dumps( sh_vlan_dict, indent=4)
vlan10_name = sh_vlan_dict['ins_api']['outputs']['output']['body']['TABLE_vlanbrief']['ROW_vlanbrief'][1]['vlanshowbr-vlanname']
示例12: main
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def main():
"""
This is the main body of the script. This script reads in a file containing IP addresses and using the NX-OS API
pulls CDP information from each device (IP) and stores it in a CSV file named cdp-output.csv in the local directory.
"""
#Initialize the list data structure that will hold the IPs from the given file
ip_list = []
#Initialize the list data structure that will hold the cdp information extracted from each switch.
#This will be a list of lists.
nei_list = []
#Store the path and filename provided as the first argument in the variable "ip_file_path"
ip_file_path = sys.argv[1]
#Using the file_accessible function, make sure that the file exists before trying to open it.
ip_file_accessible = file_accessible(ip_file_path,'r')
if ip_file_accessible: # If the function file_accessible returned 'True' then the file is good and can be processed.
ip_fh = open(ip_file_path, 'r') # Open the file given as an argument which should contain one IP address per line
ip_l = ip_fh.readlines() #Use the xxx.readlines() function to read in each line of the file into a list.
# Using list comprehension populate the ip_list varialbe with valid IPs without leading or trailing CR,LF, or whitespace
# within the list comprehension command call the qa_ipformat to ensure its a properly formatted IP string
ip_list = [ip.strip() for ip in ip_l if len(ip)>0 and qa_ipformat(ip.strip())]
#print "ip_list: ", ip_list #Troubleshooting print statement. Should be commented out of working code.
else: # if the file_accessible function returned 'False' the file provided is not accessible and the script should end gracefully.
#Function returned Fals so the file does not exist. Print error and exit out of script.
print("The file <" + ip_file_path + "> cannot be found. Please verify path and file name and try again.")
sys.exit() #The file given in the command line is not accessible so print a notification and exit out of the script.
# Define credentials to use for devices
un = 'admin'
pw = 'cisco123'
#Header line printed to stdout (screen) to inform the user of what the script is doing.
print "\n" + "="*20 + "Processing Devices in file " + ip_file_path + "="*20
for dev_ip in ip_list: #This for loop interates through each element of the list ip_list
#print "\nProcessing device with IP: ",ip
# Using the imported function Device in module device define the parameters to establish a session with the device.
dev = Device(ip=dev_ip,username=un,password=pw)
# Open a session to the device
dev.open()
# Run the 'show version' command to get the hostname of the device
# First get the output of the command
sh_ver_cmd_out = dev.show('show version')
host_name = get_hostname(sh_ver_cmd_out)
print "hostname from main(): ",host_name
# Run the 'show cdp neighbor' command on the device and store the resulting output in cdp_cmd. This will return a tuple of dictionaries.
cdp_cmd = dev.show('show cdp neighbor')
# Take the command output stored in the second tuple [1] and store it in xlm format in the cdp_out variable
# The cdp_out variable now has the actual 'show cdp neighbor' data
cdp_out = xmltodict.parse(cdp_cmd[1])
#print json.dumps(cdp_out, indent=3) #Troubleshooting print statement. Should be commented out of working code.
# Using the json.dumps output to determine the structure of the cdp_out dictionary or the "path" that must be walked to get to the values needed
# The cdp_nei_list is a list of dictionaries. Each element describes the neighbor information.
cdp_nei_list = cdp_out['ins_api']['outputs']['output']['body']['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info']
#print "cdp_nei_list: ", cdp_nei_list #Troubleshooting print statement. Should be commented out of working code.
#print "lenght of cdp_nei_list: ",str(len(cdp_nei_list)) #Troubleshooting print statement. Should be commented out of working code.
# Interate through each element of the list which contains a dictionary describint each cdp neighbor entry.
for nei in cdp_nei_list:
#print nei
#Print the IP of the current switch, the id of the neighbor, the local interface, the platform of the neighbor and the neighbor or remote interface
print dev_ip,nei['device_id'],host_name, nei['intf_id'],nei['platform_id'],nei['port_id']
#record the values printed in a CSV format so each row describing a neighbor can be saved to a file at the end of processing
nei_list.append(dev_ip + "," + host_name + "," + nei['device_id'] + "," + nei['intf_id'] + "," + nei['platform_id'] + "," + nei['port_id'] + "\n")
#print nei_list #Troubleshooting print statement. Should be commented out of working code.
#print len(nei_list) #Troubleshooting print statement. Should be commented out of working code.
# Open a file that will be used to Write the neighbor results and name it 'cdp-output.csv'
out_fh = open('cdp-output.csv','w')
out_fh.write("Local IP, Local Hostname, Remote Hostname, Local Interface, Remote Model, Remote Interface \n")
# Iterate through the nei_list list data structure and write a line to the output file for each element in the list representing a neighbor.
for row in nei_list:
# This command writes one "row" to the 'cdp-output.csv' file
out_fh.write(row)
# Close the cdp-output.csv file
out_fh.close()
示例13: Device
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
#!/usr/bin/env python
import xmltodict
from device import Device
if __name__ == "__main__":
switch = Device(ip='192.168.200.50')
switch.open()
my_data = switch.show('show cdp neighbors')
result = xmltodict.parse(my_data[1])
cdp_table = result['ins_api']['outputs']['output']['body'] \
['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info']
for each_neighbor in cdp_table:
print '=' * 40
for key, value in each_neighbor.iteritems():
if key == 'intf_id': print 'Local Interface: ', value
if key == 'device_id': print 'Neighbor: ', value
if key == 'port_id': print 'Neighbor Interface: ', value
print '=' * 40
示例14: main
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
def main():
args = sys.argv
if len(args) == 4:
#This section will check to see if the file pass to Python in a argument actually exists
if os.path.exists(args[1]):
switch_ips = open(args[1]).read().splitlines()
else:
print 'File ', os.path.realpath(args[1]), 'does not exist. Please try again'
sys.exit(1)
#For look to open each switch in the list of IP addresses passed via CLI arguments
for switch_ip in switch_ips:
switch = Device(ip=switch_ip,username=args[2],password=args[3])
switch.open()
#These lines gat the XML output from the XML API on the N9K
getswitchhardwaredata = switch.show('show hardware')
getswitchvpcdata = switch.show('show vpc')
getvpccondata = switch.show('show vpc consistency-parameters global')
#These lines parse the XML into JSON format
getswitchvpcdatajson = xmltodict.parse(getswitchvpcdata[1])
getswitchhardwaredatajson = xmltodict.parse(getswitchhardwaredata[1])
getvpccondatajson = xmltodict.parse(getvpccondata[1])
#This grabs the name on the switch
switchname = get_hostname(getswitchhardwaredatajson)
#<<<This is the start of outputting information regarding a switch>>>
print '=' * 20, switchname, '=' * 20
#This sends the show vpc command and show vpc con global command JSON data to the function to check for problems.
#This will also return a list of the indivdual vPCs that are configured on the switch.
vpcinfo = vpc_check(getswitchvpcdatajson,getvpccondatajson)
#Calls a function to return the vPC IDs from the switch.
vpc_list = list_vpc_nums(vpcinfo)
#Now we take the list of vPC IDs and call the NXAPI with the command show vpc con vpc X
vpc_error_count = 0
for each in vpc_list:
stringeach = str(each)
string_cmd = 'show vpc consistency-parameters vpc '
string_cmd += stringeach
#This line takes the string_cmd variable and uses that to run the commmand with the customer VPC ID
getvpccondetail = switch.show(string_cmd)
#Parse the XML to JSON
getvpccondetailjson = xmltodict.parse(getvpccondetail[1])
#This calls a function to check each indivdual vPC for inconsistencies
is_vpc_error = vpc_con_check(each,getvpccondetailjson)
if is_vpc_error == True:
vpc_error_count +=1
#This section will monitor if any vPCs returned mismatches, if none did, then it prints there were no errors.
if is_vpc_error == False:#
if vpc_error_count == 0:
print '===No vPC consistency issues===\n'
#<<<This is the end of outputting information regarding a switch>>>
print '=' * 20, switchname, '=' * 20 , '\n'
else:
print 'ERROR: Invalid syntax\n'\
'Example: \"python vPCconcheck.py file.txt username password\"'
sys.exit(1)
示例15: Device
# 需要导入模块: from device import Device [as 别名]
# 或者: from device.Device import show [as 别名]
# Nexus IP, Credentials, and Open NX-API Connection
#
n9k = Device(ip=n9k_ip, username=n9k_user, password=n9k_pass)
n9k.open()
# Open file(s) for collecting output data
#
f_intstat = open('intstat.dat', "w")
f_swprts = open('swprts.dat', "w")
f_ipprts = open('ipprts.dat', "w")
f_hard = open('hardware.dat', "w")
# Collect & print "show hardware output
#
sh_hardware = n9k.show('show hardware')
hardware_dict = xmltodict.parse(sh_hardware[1])
hw_data = hardware_dict['ins_api']['outputs']['output']['body']
hw_data_output = json.dumps( hardware_dict, indent=4)
hw_dict = {}
hw_dict['os_version'] = hw_data['kickstart_ver_str']
hw_dict['type'] = hw_data['chassis_id']
hw_dict['memory'] = hw_data['memory'] + hw_data['mem_type']
hw_dict['hostname'] = hw_data['host_name']
hw_dict['bootflash'] = hw_data['bootflash_size']
hw_dict['last_reboot_reason'] = hw_data['rr_reason']
hw_dict['uptime'] = '{} day(s) {} hour(s) {} min(s) {} sec(s)'.format(hw_data['kern_uptm_days'],hw_data['kern_uptm_hrs'],hw_data['kern_uptm_mins'],hw_data['kern_uptm_secs'])
ser_nums = {}
ser_nums_data = hardware_dict['ins_api']['outputs']['output']['body']['TABLE_slot']['ROW_slot']['TABLE_slot_info']['ROW_slot_info']
for each in ser_nums_data:
if 'serial_num' in each.keys():