Archive

Posts Tagged ‘python3’

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 🙂

 

 

Advertisements

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: 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: , , ,

Learning Python: Week1 (Preliminaries and Strings)

15 Apr 2017 Leave a comment

 

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.

Kirk discussed about the string methods in first week ,where he also put some exercise for us to work upon.The exercise seems to be simple for python experts ,but its  good learning exercise for the beginners who are in process of learning Python.

This post will focus only on the python exercise  for week 1.

Exercise:

1 ) Need a python script where user echo an input as IPv4 address and our task is to split into its octets.

 

Code

1c

Output

1o

 

We have used the system specific function  defined to get the user input and print the output. Sys.stdin is used for all interactive input by user whereas sys.stdout is used for the output of the same.

Here we are using echo to send the data to sys.stdin .We have entered input as  “Hello ! How are You” .Which gets print out the text on screen.

We can also used the fileinput.input() function to read the file or interactive input by user, same shown in below code.

We have to modify the code so that user enter the Ipv4 address and get the Ip address to be split into octets

 

Code

2c

Output

2o

 

We have used string method line.split() to split the ip address into octets. But here comes the new problem ,we don’t want newline character ‘\n’ in output. We need to get rid of the same.

 

Code

3c

As in above mentioned code ,I tried to used string method string.rstrip(‘\n’) on the output list ,but it gave error ‘list object has no attribute ‘rstrip’

That means list does not support rstrip().

So it makes us to think further other method to get rid of newline character ‘\n’. There are two ways to achieve the required result.

 

Code-way1

4c

Output

4o

Above code has used  the rstrip() method on the specific  element of the list  rather than whole list

 

Code-way2

5c

Output

5o

 

We have modified the code as shown above  , we are working first to get rid of the newline character by using the rstrip() method on the initial  string input by user and then going for the strip of the ip address into different octets resulting output as a list . It Seems more straight forward 🙂

 

Exercise 2

 

  1. Use the split method to divide the following IPv6 address into groups of 4 hex digits (i.e. split on the “:”) FE80:0000:0000:0000:0101:A3EF:EE1E:1719 and use join method to reunite your split IPv6 address back to its original value.

 

Its bit simple , if you gone through last exercise . It is a easy part just need to use the split() and join() method to do the needful.

 

Code:

6c

Output :

6o

 

 

 

%d bloggers like this: