SDN : APIC Vs APIC-EM

Software Defined Network (SDN) is technology to allow network devices to be managed through software application, thus making configuration process automated and faster.

Network devices have its own management plane, data plane and control plane. Traditional SDN decouples Control plane from all different devices and have all these control plane go live inside  SDN controller so the controller now take care of control plane  and run the routing protocols and do all the control plane related stuff and administer or push instructions down the devices.

TRADITIONAL SDN :

 

 

This type of SDN is known as stateful approach where SDN controller acts as a control plane for each network device it manages. The SDN controller is responsible for translating policies into commands and pushed to the devices.

SDN controller communicates with the below devices through southbound interfaces .One of the popular SDN controller is called Open Daylight.

Open Daylight is an open source SDN platform, which can use the OpenFlow protocol protocol as Southbound Application programming interface(API) to communicate with network devices that support Openflow  protocol.

We have just talked about the south of controller, north of controller is the applications which communicates to controller through NorthBound Interfaces. Applications can use REST API to communication through Northbound Interface to controller.

REST (REpresentational State Transfer) APIs allows to communicate with SDN controller using http or https .Postman is such one of the application which can be used to communicate the SDN Controller through Northbound interface.

CISCO  takes a bit different approach of  their controller APIC (Application Policy Infrastructure Controller ) and APIC-EM(Enterprise Module) .

APIC and APIC-EM have control plane back to the devices means that control plane is not decoupled from the network devices as in traditional SDN.

Cisco Controller is Stateless approach where each network device has its own control Plane. SDN Controller send policies to the network devices, which are individually responsible for translating policies into commands.

APIC :

 

 

 

APIC-EM 

This is APIC which is seen in Data center whereas APIC –EM is generally seen in Campus, LAN or remote offices.

The best part of the APIC-EM is that it can communicate with our traditional devices which do not speak open flow , means that there is no requirement to run Open Flow through southbound interface to communicate with network devices which does not speak SDN languages.

 

 

APIC –EM communicate to network devices through southbound interface using TELNET,SSH or SNMP. Whereas Northbound Interface still communicates with APIC-EM using  REST  APIs so in Nutshell Application can send the instruction  to APIC-EM  through Northbound interface using REST APIs ,further APIC-EM push  instructions  to get the required information through Southbound Interface using SSH, TELNET or SNMP which is generally OpenFlow in case of APIC .

 

Characteristics of APIC

  • For use in Data Centers
  • Typical Applications found on APIC:
    • Policy Manager : Contains policy and rules that can be applied to end point groups
    • Topology Manager :Maintains Information about the topology
    • Observer :Does Monitoring of ACI Components.
    • Boot Director :Used for firmware update and booting of spine or leaf.
    • Appliance Director :Responsible for set and control APIC cluster
    • VM Manager :This acts as intermediator between hypervisor and platform such as openstack.
    • Event Manager :Stores events and faults.
    • Appliance Element :Manages individual controller

 

APIC DASHBOARD

 

APIC-EM is generally used in 2- Tier infrastructure where core and distribution switches are collapsed together.

Characteristics of APIC-EM

  • For use in campus ,LAN or WAN
    • Network Topology Visualization: Dynamically Learn Topology and give maps.
    • CISCO IWAN :Help to set up IWAN
    • Path Trace Application: It get path trace from any Point A to any point B.

APIC-EM Dashboard

 

Hope this post helped to get basic insight of Traditional SDN and CISCO approach  based APIC and APIC-EM and most importantly the difference between APIC and APIC-EM

Smiles 🙂

Advertisements
Categories: SDN Tags: , , , ,

Nexus 9K –ACI Mode – PART 2

31 May 2017 Leave a comment

Welcome to part 2 of ACI series,  if you want to go through  part 1 of ACI series , here is link for reference  https://crazyrouters.wordpress.com/2017/05/22/nexus-9k-aci-mode-part-1/

Let’s start with the discussion of new terms related to ACI which will be used further during ACI discussion.

1.png

 

Above Pic tells about the different relation between Tenant and other components. So the first question arise is “What is actually Tenant? “

Tenant

Customer in service provided environment is same as tenant represent in Nexus-ACI .The terminology is different but concept is same, Tenant may be understood as customer, organization or domain in enterprise.

We will configure different Bridge-Domain, Vrf, Application profile, contract and filter under the Tenant.

 

VRF

VRF can be understood same as the VRF in Service provide J .VRF defines layer 3 address domain, one or more Bridge-domain cane be associated with VRF.So next question comes to mind, what is Bridge-domain?

 

Bridge-Domain (BD)

Bridge-Domain represent layer 2 domain within fabric construct .Bridge-Domain must be linked to VRF, It is simply a container for subnets.

Consider VRF defining a unique IP address space, that address space consists of multiple subnets .These subnets can be defined in one or more bridge-domain that reference the VRF.

Bridge-Domain are in fact VXLANS (would be discussing the VXLAN in detail on next post), that allows any-to-any communication irrespective whether the communicating devices are on same subnet or not. The Important point to note is that all routing is host based, no need to worry whether devices are in same subnet or whereas in traditional routing, the IP address is important because the routing is based on subnet routing. Cool Feature J .

 

Endpoint Groups

EPGs are collection of similar endpoint representing logical grouping of objects that require a similar policy. Endpoints are devices that are connected to networks directly or indirectly.  Endpoint examples include servers, virtual machines, network-attached storage, or clients on the Internet.

An EPG can be statically configured by an administrator in the APIC, or dynamically configured by an automated system such as vCenter or OpenStack

 

Policy always applies to EPGs, never to individual endpoint.

Case 1: End point within the same EPGs can communicate freely.

Case 2: End point between the different EPGs cannot communicate freely, there is need to contract   between different EPGs. So what is Contract?

 

Contract

Contract can be referred as policy construct defining type of traffic that can be pass between EPGs.. When an EPG consumes a contract, the endpoints in the consuming EPG may initiate communication with any endpoint in an EPG that is providing that contract.

Contract is must for any communication between EPGs .Contract will refer to one or more filters.

2

Contract has some sub-component

  • Subject : Group of filters that apply to specific application or service
  • Filters : Used to classify traffic
  • Actions: Defines actions, which need to perform on filter ,permit, deny, mark all are actions.

 

Let’s take an example to understand the contract and its sub-component .Consider a server  for Web services ,let’s call as Web server which might be producing  sub applications such as HTTPS,HTTP,FTP,TFTP and so on. We have requirement to impose different policy on these different sub applications .APIC defines these sub applications or services as subjects. In other words, subjects are combined within contracts to represent the set of rules that define how an EPG communicates with other EPGs.

Filters are further define under subject like access-list for endpoint groups. What operation need to be done on filters is defined by Actions

 

 

3.png

 

 

Application Profile

Application profiles are group of EPGs and the policies that define the communication between the groups. For example, Finance application may require a web server, App server, DB server, and access to outside network to enable application transaction .This application profile contain all the necessary EPGs that are logically bind to provide the application.

A group of physical and virtual server may be grouped together in a single tier or 3 tier application. The communication between these 3 tier is necessary to make up complete application, This complete application definition is known as Application profile.

 

4.png

It is necessary to create filters within our tenant that will be utilized by the contract. These contract will be used by different EPGs to complete 3 tier application profile.

We are all most done with the major terms or components involved .Hope this post have help you to get basic insight of different components of ACI.

Smiles 🙂

 

 

Categories: SDN Tags: , , , , , ,

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: , ,
%d bloggers like this: