Archive

Archive for the ‘Routing’ Category

Learning Python: Week3 (Conditionals and For Loops) -Part 4

28 May 2017 Leave a comment

As discussed in post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

This post will focus on Week 3 (Conditionals and For Loops) .This post will focus on exercise 3

##################### EXERCISE ########################

IV. Create a script that checks the validity of an IP address.  The IP address should be supplied on the command line.
A. Check that the IP address contains 4 octets.
B. The first octet must be between 1 – 223.
C. The first octet cannot be 127.
D. The IP address cannot be in the 169.254.X.X address space.
E. The last three octets must range between 0 – 255.

For output, print the IP and whether it is valid or not.

#############END ########

 

In this exercise, user will enter IP address on the command line and will be checked for valid IP address depending over the conditions.

So let’s start with code to get the IP address on the command line from user using sys.argv.

As discussed in last exercise ,if the input is more than 2 argument, it will throw output as “Error Made”

import sys

if len(sys.argv) == 2:
 ip_addr = sys.argv.pop()
 print("The IP address is :",ip_addr)
else:
 print("Error Made")

If we run the above code , we will get the output as below

C:\Users\609807949\Documents\Personal\Python\kirk\week 3>py test1.py 10.10.10.1

The IP address is : 10.10.10.1

if more than 2 argument entered by user

C:\Users\609807949\Documents\Personal\Python\kirk\week 3>py test1.py 10.10.10.1
20.20.20.1
Error Made

So we have got the input as Ip address on the command line from user. Let’s split each octet of  ip address using split () method

ip_addr_new = ip_addr.split('.')

We have used the Nested If else loop to check all the below required conditions

A. Check that the IP address contains 4 octets.
B. The first octet must be between 1 – 223.
C. The first octet cannot be 127.
D. The IP address cannot be in the 169.254.X.X address space.
E. The last three octets must range between 0 – 255.

if (len(ip_addr_new)) == 4:
 if (int(ip_addr_new[0]) > 1 and int(ip_addr_new[0]) < 223 and int(ip_addr_new[0]) != 127):
 if (int(ip_addr_new[0]) != 169 and int(ip_addr_new[1]) != 254):
 if (int(ip_addr_new[1]) >0 and int(ip_addr_new[1])< 255 and int(ip_addr_new[2]) >0 and int(ip_addr_new[2]) < 255 and int(ip_addr_new[3]) >0 and int(ip_addr_new[3])< 255 ):
 print("Ip address is valid")
 else:
 print("Ip address is Invalid")
 else:
 print("Ip address is Invalid")
 else:
 print("Ip address is Invalid")
else:
 print("Ip address is Invalid")

 

Following   code Checks for condition A  that the IP address contains 4 octets.

if (len(ip_addr_new)) == 4:

 

Further belowcode Checks for condition B and C the first octet must be between 1 – 223 and first octet cannot be 127.

if (int(ip_addr_new[0]) > 1 and int(ip_addr_new[0]) < 223 and int(ip_addr_new[0]) != 127) :

Code to Check for condition D  that the IP address cannot be in the 169.254.X.X address space.
if(int(ip_addr_new[0]) != 169 and int(ip_addr_new[1]) != 254):

Now remains the last condition E that the last three octets must range between 0 – 255.

 if (int(ip_addr_new[1]) >0 and int(ip_addr_new[1])< 255 and int(ip_addr_new[2]) >0 and int(ip_addr_new[2]) < 255 and int(ip_addr_new[3]) >0 and int(ip_addr_new[3])< 255):

So we are done with all the required conditions, if any above mentioned condition fails , we should get output as “Error” otherwise output as “Valid IP”

Here is the Code from scratch for this exercise.

exercise3.PNG

Let’s check for each condition by providing valid and invalid input.

 

exercise3_out.PNG

Method 2 

The above code is not concise , lets have better code for same problem

Let’s start from scratch ,

import sys

if len(sys.argv) != 2:
 sys.exit("Usage: ./scriptarg2.py ")

ip_add = sys.argv.pop()

As discussed earlier, It will exit the script , if argument is not equal to 2 , further userlast input will be pop into ip_add

Lets define valid_ip as true , we will using for genuine ip address.

valid_ip =True

valid_ip =True

 

As user input is in decimal format , we need to split each octet

octets = ip_add.split('.')

Now lets check condition A  i.e length of octet should be 4.

if (len(octets)) != 4:
 sys.exit("The number of octet is invalid: ")

we will use for loop to get each octet and store them in different variable , also changing the type of each element into int as we will be performing checks on basis of integer

for i , octet in enumerate(octets):
 try:
 octets[i] = int(octet)
 except ValueError:
 sys.exit("\n\nInvalid IP address: {} \n".format(ip_add))

first_octet, second_octet, third_octet, fourth_octet = octets

Now task remains to check all the required conditions for input to be valid Ip address.

First checked the valid condition for first octet.

if first_octet &lt; 1:
 valid_ip = False
elif first_octet &gt; 223:
 valid_ip = False
elif first_octet == 127:
 valid_ip = False

 

Below code checks the condition that the IP address cannot be in the 169.254.X.X address space.

if first_octet == 169 and second_octet == 254:
 valid_ip = False

 

Now remains the last condition that the last three octets must range between 0 – 255.

for octet in (second_octet, third_octet, fourth_octet):
 if (octet &lt; 0) or (octet &gt; 255):
 valid_ip = False

Lets print whether the provided IP address is valid or not

if valid_ip:
 print ("\n\nThe IP address is valid:{}".format(ip_add))
else:
 sys.exit("\n\nInvalid IP address: {}".format(ip_add))

Overall Code

import sys

if len(sys.argv) != 2:
sys.exit("Usage: ./scriptarg2.py ")

ip_add = sys.argv.pop()

valid_ip =True


octets = ip_add.split('.')

if (len(octets)) != 4:
sys.exit("The number of octet is invalid: ")


for i , octet in enumerate(octets):
try:
octets[i] = int(octet)
except ValueError:
sys.exit("\n\nInvalid IP address: {} \n".format(ip_add))

first_octet, second_octet, third_octet, fourth_octet = octets

if first_octet < 1:
valid_ip = False
elif first_octet > 223:
valid_ip = False
elif first_octet == 127:
valid_ip = False

if first_octet == 169 and second_octet == 254:
valid_ip = False


for octet in (second_octet, third_octet, fourth_octet):
if (octet < 0) or (octet > 255):
valid_ip = False

if valid_ip:
print ("\n\nThe IP address is valid:{}".format(ip_add))
else:
sys.exit("\n\nInvalid IP address: {}".format(ip_add))

So done with this exercise , will be back with new post .

smiles 🙂

 

 

Nexus 9K –ACI Mode – PART 1

22 May 2017 1 comment

 

SDN is the Buzzword for Network Guys, How is it related to Nexus 9k in API mode.

Let’s Start with SDN to understand the co–relation between SDN and Nexus 9K (ACI Mode).

To understand SDN in network terms, SDN does decoupling of control plane and data Plane, thus decision making now done at centralized control plane with the help of software. This SDN technology can be termed as classical SDN.

Nexus 9K(SDN Implementation ) behaves in different way than classical SDN,  no decoupling of control and Data plane is done, but a policy agent is added  over control and data plane.

APIC (Application Policy Infrastructure Controllers) interact with Policy agent on Nexus 9K to push the required policy. Thus ACI can be said to be based of two component:

  1. Nexus 9k which forms the physical infrastructure
  2. APIC which takes care and control all aspects of fabric configuration.

 

APIC is neither the control plane nor data plane but the policy controller which holds the defined policy and can instantiate required policy.

 

 

1

Interesting part of the NEXUS 9K (ACI Mode) is that you cannot run config t on the device , the only method to config the nexus 9K is via APIC or GUI.

ACI used leaf and spine topology, where each leaf is connected to spine node in fabric and there is no direct connectivity between leaf to leaf or spine to spine. The model is well known as CLOS Model.

 

2.png

MCP (Mis Cabling Protocol) runs to avoid any interconnected between leaf. The leaf node goes to suspend in case leaf are connected to each other directly by mistake.

Traffic with the source and destination on the same leaf is treated locally, whereas all other traffic passes from ingress to egress leaf via spine switch.

All external connectivity i.e host, server, VM, router, switches etc is via leaf nodes only.

The APIC REST API is a programmatic interface to the APIC that uses REST architecture. The API accepts and returns HTTP or HTTPS messages that contain JSON or XML documents.  In other words all ACI fabric functionality is defined by the Northbound REST API and the message pushed is in form of XML or JSON.

There are different new terms involved in ACI such as Tenant, End point, Contract, application profile, switch profile, interface profile ,VXLAN ,etc  which  will be discussed in coming posts.

Smiles 🙂

Categories: Routing

Learning Python: Week3 (Conditionals and For Loops) -Part 3

22 May 2017 Leave a comment

As discussed in post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

This post will focus on Week 3 (Conditionals and For Loops) .This post will focus on exercise 2

################EXERCISE 2 #########################

III. You have the following ‘show ip int brief’ output.

show_ip_int_brief = ”’
Interface            IP-Address      OK?     Method      Status     Protocol
FastEthernet0   unassigned      YES     unset          up          up
FastEthernet1   unassigned      YES     unset          up          up
FastEthernet2   unassigned      YES     unset          down      down
FastEthernet3   unassigned      YES     unset          up          up
FastEthernet4    6.9.4.10          YES     NVRAM       up          up
NVI0                  6.9.4.10          YES     unset           up          up
Tunnel1            16.25.253.2     YES     NVRAM       up          down
Tunnel2            16.25.253.6     YES     NVRAM       up          down
Vlan1                unassigned      YES    NVRAM       down      down
Vlan10              10.220.88.1     YES     NVRAM       up          up
Vlan20              192.168.0.1     YES     NVRAM       down      down
Vlan100            10.220.84.1     YES     NVRAM       up          up
”’

From this output, create a list where each element in the list is a tuple consisting of (interface_name, ip_address, status, protocol).  Only include interfaces that are in the up/up state.

Print this list to standard output.

##################### END #######################

Here we have been provided with huge string having the “sh ip int brief” command output.We have to create a list of up interfaces only.

First we will seperate each line by using “\n” in  string split method

out = show_ip_int_brief.split(‘\n’)

>>> show_ip_int_brief = '''
Interface IP-Address OK? Method Status Protocol
FastEthernet0 unassigned YES unset up up
FastEthernet1 unassigned YES unset up up
FastEthernet2 unassigned YES unset down down
FastEthernet3 unassigned YES unset up up
FastEthernet4 6.9.4.10 YES NVRAM up up
NVI0 6.9.4.10 YES unset up up
Tunnel1 16.25.253.2 YES NVRAM up down
Tunnel2 16.25.253.6 YES NVRAM up down
Vlan1 unassigned YES NVRAM down down
Vlan10 10.220.88.1 YES NVRAM up up
Vlan20 192.168.0.1 YES NVRAM down down
Vlan100 10.220.84.1 YES NVRAM up up
'''
>>> out = show_ip_int_brief.split('\n')
>>>
>>> print(out)
['', 'Interface IP-Address OK? Method Status Protocol', 'FastEthernet0 unassigned YES unset up up', 'FastEthernet1 unassigned YES unset up up', 'FastEthernet2 unassigned YES unset down down', 'FastEthernet3 unassigned YES unset up up', 'FastEthernet4 6.9.4.10 YES NVRAM up up', 'NVI0 6.9.4.10 YES unset up up', 'Tunnel1 16.25.253.2 YES NVRAM up down', 'Tunnel2 16.25.253.6 YES NVRAM up down', 'Vlan1 unassigned YES NVRAM down down', 'Vlan10 10.220.88.1 YES NVRAM up up', 'Vlan20 192.168.0.1 YES NVRAM down down', 'Vlan100 10.220.84.1 YES NVRAM up up', '']
>>>

So we get list out [] having  elements  as above. We can see first and last element as blank space.lets remove the first and last element

>>> out1 =out[1:-1]
>>>
>>> print(out1)
['Interface IP-Address OK? Method Status Protocol', 'FastEthernet0 unassigned YES unset up up', 'FastEthernet1 unassigned YES unset up up', 'FastEthernet2 unassigned YES unset down down', 'FastEthernet3 unassigned YES unset up up', 'FastEthernet4 6.9.4.10 YES NVRAM up up', 'NVI0 6.9.4.10 YES unset up up', 'Tunnel1 16.25.253.2 YES NVRAM up down', 'Tunnel2 16.25.253.6 YES NVRAM up down', 'Vlan1 unassigned YES NVRAM down down', 'Vlan10 10.220.88.1 YES NVRAM up up', 'Vlan20 192.168.0.1 YES NVRAM down down', 'Vlan100 10.220.84.1 YES NVRAM up up']
>>>

So now we have get the new list out1 , now we will work upon the list out1.

We will take each element and split further using split() method which will split each element futher so example ‘FastEthernet0 unassigned YES unset up up’ is element which will be further split into ‘FastEthernet0’ ‘unassigned’ ‘YES’ ‘unset’ ‘up’ ‘up’.

we will use for loop to execute the same. But before that we can see that we element[0] i.e ‘Interface IP-Address OK? Method Status Protocol’ is of no use , we don’t need any data from it. So we can continue to next element and then perform split operation next element onwards.

>>> for i , element in enumerate(out1):
if "interface" in element:
countinue

out_split = element.split()

We want the only Interace, Ip-Address ,Staus and Protocol , lets store the required out in variable

if_name, ip_addr, OK?, Method, line_status, line_proto = out_split

Last part is to discard Ok? and Method  , that can be done appending the only required value in respective variable, that can be done by appending into new list line[].

if_name, ip_addr, OK, Method, line_status, line_proto = out_split
if (line_status == 'up') and (line_proto == 'up'):
line.append((if_name, ip_addr, line_status, line_proto))

Now we have to print the output in more better way using pprint() function.

pprint.pprint(line)

So Here is final code and  corresponding output.

Code:

import pprint

show_ip_int_brief = '''
Interface IP-Address OK? Method Status Protocol
FastEthernet0 unassigned YES unset up up
FastEthernet1 unassigned YES unset up up
FastEthernet2 unassigned YES unset down down
FastEthernet3 unassigned YES unset up up
FastEthernet4 6.9.4.10 YES NVRAM up up
NVI0 6.9.4.10 YES unset up up
Tunnel1 16.25.253.2 YES NVRAM up down
Tunnel2 16.25.253.6 YES NVRAM up down
Vlan1 unassigned YES NVRAM down down
Vlan10 10.220.88.1 YES NVRAM up up
Vlan20 192.168.0.1 YES NVRAM down down
Vlan100 10.220.84.1 YES NVRAM up up
'''

out = show_ip_int_brief.split('\n')

#print(out)

line =[]

out1 =out[1:-1]
for i , element in enumerate(out1):
if "interface" in element:
countinue

out_split = element.split()

if_name, ip_addr, OK, Method, line_status, line_proto = out_split
if (line_status == 'up') and (line_proto == 'up'):
line.append((if_name, ip_addr, line_status, line_proto))

pprint.pprint(line)

 

OUTPUT:

[('FastEthernet0', 'unassigned', 'up', 'up'),
('FastEthernet1', 'unassigned', 'up', 'up'),
('FastEthernet3', 'unassigned', 'up', 'up'),
('FastEthernet4', '6.9.4.10', 'up', 'up'),
('NVI0', '6.9.4.10', 'up', 'up'),
('Vlan10', '10.220.88.1', 'up', 'up'),
('Vlan100', '10.220.84.1', 'up', 'up')]

 

So here we are done with the Exercise 2 , will be back with exercise 3.

Smiles 🙂

 

 

 

 

 

 

Categories: Python, Routing Tags: ,

Learning Python: Week3 (Conditionals and For Loops) -Part 2

14 May 2017 Leave a comment

As discussed in post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

This post will focus on Week 3 (Conditionals and For Loops) .This post will focus on exercise 1

######################## EXERCISE 1 #######################

I. Create an IP address converter (dotted decimal to binary).  This will be similar to what we did in class2 except:

    A. Make the IP address a command-line argument instead of prompting the user for it.
        ./binary_converter.py 10.88.17.23

    B. Simplify the script logic by using the flow-control statements that we learned in this class.

    C. Zero-pad the digits such that the binary output is always 8-binary digits long.  Strip off the leading ‘0b’ characters.  For example,

        OLD:     0b1010
        NEW:    00001010

    D. Print to standard output using a dotted binary format.  For example,

        IP address          Binary
      10.88.17.23          00001010.01011000.00010001.00010111

    Note, you might need to use a ‘while’ loop and a ‘break’ statement for part C.

        while True:
            …
            break       # on some condition (exit the while loop)

    Python will execute this loop again and again until the ‘break’ is encountered. 

############################ END ##############################

 

Most of the part of this exercise is repeated one from last exercise done in week 2.

Lets take step by step , first we need a command line argument instead of prompting from the user, this can be done be sys,argv (discussed in last post )

 

scriptarg1

 

Here we are getting input from command line, restricted input not more than 2 argument.if we tried to give more than 2 argument from command line, it will through a error.

Output:

scriptarg1_out

Now we need to split the entered IP address using split method and then convert into binary. Its same as we did in week 2 exercise.

raw_input=ip_addr.split('.')

 

Above code will split the ip address into element of list separated by ‘.’ .

We will also define a list which we will be using afterward to store the ip octet converted into binary.

ip_add_new =[]

 

We will use the for loop to go through each octet of Ip address and convert into binary

for i, element in enumerate(raw_input):
 octet = (bin(int(raw_input[i])))

we will get the output as below

0b11000000
0b10101000
0b1010
0b1

Its the Binary conversion of each octet of ip address. So we are done with part a and b of exercise .Now we need to zero-pad the digits such the binary output is always 8-binary digits  longs i.e strip off the leading ‘ob’ characters from above output.

Lets first remove the ‘ob’ from each binary converted octet ,this can be easily done by string slicing.

octet_new = octet[2:]

 

octet_new will have now have binary representation of ip octet without first two character of string i.e ‘ob’ that are at index 0 and index 1.

In short , now octet_new will have following values

 0 octet   11000000 
 1 octet   10101000 
 2 octet   1010 
 3 octet   1 

so ‘ob’ is removed from each octet’s binary output.

Now we have the make each octet with zero-pad such that binary output is eight digit.

so for that we run while loop , it checks for the length of octet and gets output as if condition fails (len(octet_new) >=8:).

if condition true , it will run the while loop adding the ‘o’ to the octet binary till length of binary output becomes 8.I also need to append the element into the list which i have defined earlier i.e ip_add_new =[] with each iteration.

 

 

for i, element in enumerate(raw_input):
octet = (bin(int(raw_input[i])))
print(octet)
octet_new = octet[2:]
print(octet_new)
while True:
if len(octet_new) >=8:
break
octet_new = '0'+ octet_new
print(octet_new)
ip_add_new.append(octet_new)

 

so only  thing to focus is to join all four octet of binary representation using ‘.’

that can be easily done using  ‘.’.join method

ip = '.'.join(ip_add_new)

Now print the output using format method

 

print("\n")
print("{:20}{:20}".format("IP address","Binary"))
print("{:20}{:20}".format(ip_addr,ip))

Here is the Code from scratch for this exercise.

exercise1.png

OUTPUT:

exercise1_out

So here we are done with the Exercise 1 , will be back with exercise 2.

Smiles 🙂

     

 

 

Learning Python: Week3 (Conditionals and For Loops) -Part 1

14 May 2017 Leave a comment

As discussed in post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

This post will focus on Week 3 (Conditionals and For Loops)  Exercises. As Usual , lets start with notes and will focused on exercise in next post.

If Else Condition:

How can you say that any condition is true or false ? Lets first understand different scenarios with examples.

Empty String (‘  ‘)       >>>> False  , any other string case       >>>> True

0  and 0.0                    >>>>> False , all other number value >>>>>True

Blank list [ ]               >>> False , all other list value              >>>>> True

Blank Tuple()            >>>False , all other tuple value                 >>>True

Blank Dictionary {} >>> False , all other dictionary  value    >>> True

Few more example:

1

IF Else Syntax:

if expression 1:
statement
statement
statement

elif expression 2:
statement
statement
statement

else expression 3:
statement
statement
statement

Outside of if else condition

If expression 1 is true , process the statement below it and come out of the if else loop , if expression 1 is false , check for condition for expression 2 , if true ,process the statement below and come out of if else loop, otherwise check for condition for expression 3 and if true ,process the statement below it otherwise come out of if else loop and process .

Its better to avoid the nested loop , if loop goes beyond level 3. Try to replace the nested loop with more simple code .

2.PNG

Above code can be replaced with more simple and convenient code as below.

3.PNG

FOR LOOP :

Its iterate over the items of any sequence as a list or string

Code

for1

We have  list  Vendors  storing names of vendors as string , so we want to iterate over the items of list and print it.

we can take any other variable in place of vendor too  in above code .

output

for_out

we can also have the above code as below:

for2.png

This will give the same output as before

for index in range(len(vendors)):

>>> vendors = [‘cisco’,’juniper’,’alcatel’,’hp’,’adva’]
>>> len(vendors)
5
>>>
>>> range(5)
range(0, 5)

so it  iterate over the list  ‘vendors’  having total  5 elements and and print vendors element as output for each index

iteration 1 , index =0  , vendors[0]

iteration 2 , index =1  , vendors[1]

iteration 3 , index =2  , vendors[3]

iteration 4 , index =3  , vendors[4]

iteration 5 , index =4  , vendors[5]

But there is much better way to have the above codes using enumerate ,where it takes care of index as well as value .

for3.png

It will result in same output as before , but its better way to write the code.

for3_out.PNG

Nested For loop:

Lets start with  simple example  which explains the nested for loop.

for4

a and b is list having element as numbers , as below

>>> a =list(range(3))
>>> a
[0, 1, 2]
>>> a=list(range(4))
>>> b
[0, 1, 2, 3]
>>>

So each iteration of outer loop, it should go via entire inner loop till condition is satisfied, in above loop as condition  j==2 is true, its comes out of inner loop , and outer loop again starts with index value incremented by 1 ,this this process goes on as below

i = 0 , j=0 ,condition = false , print(“hello world”)
i = 0 , j=1,condition = false , print(“hello world”)
i = 0 , j=2 ,condition = true , Come out of inner loop
i = 1 , j=0 ,condition = false , print(“hello world”)
i = 1 , j=1 ,condition = false , print(“hello world”)
i = 1 , j=2 ,condition = false , Come out of inner loop
i = 2 , j=0 ,condition = false , print(“hello world”)
i = 2 , j=1 ,condition = false , print(“hello world”)
i = 2 , j=2 ,condition = false , Come out of inner loop

output:

for4_out

Note that you cannot have a for or if else loop without any statement , otherwise will get an  error !!

for i in a:

 

or

if True:

 

There are the cases where we don’t want any statement in for or if else , we can have the same by using the ‘Pass’

for i in a:

pass

or

if True:

pass

Passing argument into script:

We can pass the argument into the script.Lets start with an simple script example

CODE:scriptarg

Here we have import sys and printed sys.argv , it will print the scriptname and all the argument you entered while running this script .

OUTPUT:

scriptargout.PNG

If we want to limit the number of argument to be entered ,this can be done too as per the code below:

CODE:

scriptarg1

Here limit the argument to 2 , if more than 2 argument entered .It will show the Error

OUTPUT:

scriptarg1_out.PNG

Its been a long post , but its worth to go once through It. I will be back with EXERCISES in next post ,So be ready to crack the Exercise,.Smiles 🙂

Categories: Python, Routing Tags: , ,

Learning Python: Week2 (Printing, Numbers, and Lists) -Part 5

5 May 2017 1 comment

As discussed in post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

This post will focus on Exercise 4.

################# Exercise 4 #############

IV. You have the following string from “show version” on a Cisco router

cisco_ios = “Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version 15.0(1)M4, RELEASE SOFTWARE (fc1)”

Note, the string is a single line; there is no newline in the string.

How would you process this string to retrieve only the IOS version:

   ios_version = “15.0(1)M4”

Try to make it generic (i.e. assume that the IOS version can change).

You can assume that the commas divide this string into four sections and that the string will always have ‘Cisco IOS Software’, ‘Version’, and ‘RELEASE SOFTWARE’ in it.

############## END ##########################

 

These will be easy to get it done, if gone through last three exercise of week 2. We have given a string named cisco_ios . we need to go through the string and retreive  the IOS Version.

cisco_ios = “Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version 15.0(1)M4, RELEASE SOFTWARE (fc1)”

As we can see there are four parts of string seperated by  ‘ , ‘ , so lets use the our evergreen classic best method to separate the strings  in 4 elements of list by using  the split method.

ios_ver1

So now we are having list out with 4 elements, we have to focus on element 2 only of list out .

ios_ver2

Here we can see 2 elements separated by space , we target is second element which is literally ios_version.

ios_ver3

So we have got the required result. Lets have a code altogether to get the required result

CODE:

ios_ver_code

OUTPUT:

ios_ver_code_out

So, here we are done with exercise of week 2. Hope its was cool !!!!

smiles 🙂

 

 

 

 

Categories: NOTES, Python, Routing Tags: , , ,

Learning Python: Week2 (Printing, Numbers, and Lists) -Part 4

As discussed in last post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

This post will focus on Exercise 3

########### EXERCISE 3  #########

III. You have the following four lines from ‘show ip bgp’:

entry1 = “*  1.0.192.0/18   157.130.10.233     0 701 38040 9737 i”
entry2 = “*  1.1.1.0/24       157.130.10.233     0 701 1299 15169 i”
entry3 = “*  1.1.42.0/24     157.130.10.233     0 701 9505 17408 2.1465 i”
entry4 = “*  1.0.192.0/19   157.130.10.233     0 701 6762 6762 6762 6762 38040 9737 i”

Note, in each case the AS_PATH starts with ‘701’.

Using split() and a list slice, how could you process each of these such that–for each entry, you return an ip_prefix and the AS_PATH (the ip_prefix should be a string; the AS_PATH should be a list):

Your output should look like this:

ip_prefix             as_path                                           
1.0.192.0/18       [‘701’, ‘38040’, ‘9737’]                          
1.1.1.0/24           [‘701’, ‘1299’, ‘15169’]                          
1.1.42.0/24         [‘701’, ‘9505’, ‘17408’, ‘2.1465’]                
1.0.192.0/19       [‘701’, ‘6762’, ‘6762’, ‘6762’, ‘6762’, ‘38040’, ‘9737’]

Ideally, your logic should be the same for each entry (I say this because once I teach you for loops, then I want to be able to process all of these in one four loop).

If you can’t figure this out using a list slice, you could also solve this using pop().

############### END ################

 

Lets begin to code the requirement using pop and slice and then move to solve the exercise using for loop.

Here is the input provided , we have to get the IP prefix part and as_path extracted from each entry.

entry1 = “*  1.0.192.0/18   157.130.10.233     0 701 38040 9737 i”
entry2 = “*  1.1.1.0/24       157.130.10.233     0 701 1299 15169 i”
entry3 = “*  1.1.42.0/24     157.130.10.233     0 701 9505 17408 2.1465 i”
entry4 = “*  1.0.192.0/19   157.130.10.233     0 701 6762 6762 6762 6762 38040 9737 i”

Lets consider each entry one by one, if we are able to crack the logic for one entry ,it will be valid for all other entry .

First need to split entry1  into elements of a new  list ent1  using split method .

aspath1

Next task is to split the list into new list out1  having the same elements as ent1 excepts the first  element i.e ‘*’ and last element ‘i’.

We can do the same by using the pop method but i have used the split method to get new list out1 having the all elements except first one and last one .

aspath2

next requirement is to print the ip prefix i.e first element of list out1 and As-path which starts with element value’701′

aspath3

So we have got both ip prefix and as_path as output for entry1. so we can go ahead the same for each entry and get the required output.

Here is final code for reference

CODE:

as_path_code1.PNG

 

As you note in above code that i have changed the list into string (str(out1[3:]) for each entry  while printing the output.As we try to pass only the list , it will throw error as below ,so need to change type from list to string.

TypeError: unsupported format string passed to list.__format__

aspath4

OUTPUT:

as_path_code1_ou

So we have got the final output as required .

Lets optimise and get the same code using the for loop.

first taken each entry as element of  list named as  output.

as_for1

Now i will run the for loop for each element of output and perform the same operation on each element of list output as below:

opearation for each iteration of element of list output: 

1) Split each element of list output  into a new list out  using split method .

2)Further Split the list into new list out1  having the same elements as out excepts ‘*’and ‘i’.

3) Print the first element of list out1 as ip_prefix and slice of list out1 starting from value’701′ as as_path .

Here is the code using for loop for reference.

CODE:

as_path_for_code

OUTPUT:

as_path_for_code_out

So we are done with this exercise , using for loop and without for loop.

I will be back with last exercise of week 2 .

Smiles 🙂

 

 

 

 

Categories: NOTES, Python, Routing Tags: , , ,
%d bloggers like this: