Next Generation Network Engineers

PlAwAnSaI

Administrator
External Resources:
  • Network Transformation and Essential Skills for Next Generation Network Engineers
    www.ciscolive.com/online/connect/sessionDetail.ww?SESSION_ID=92606
  • Python Programming for Network Engineers
    www.youtube.com/playlist?list=PLhfrWIlLOoKPn7T9FtvbOWX8GxgsFFNwn
  • packetpushers.net/next-generation-network-engineers
  • Is the CCIE Dead? Programming not Configuring Future IT
    www.ciscolive.com/online/connect/sessionDetail.ww?SESSION_ID=94452
  • learninglabs.cisco.com/tracks/programming-dna
https://www.youtube.com/watch?v=e6wEhJOJ4Vw
Method of Procedure (MOP) Is Largely Manual
  • Pre-maintenance Checks
    + Manually verify system state and readiness for MOP deployment
    + No way to track/predict an impact on the network: Will I violate my SLA?
  • Maintenance
    + Node Cost out
    + Apply Software updates
    + Apply Configuration changes
    + Verity system state to ensure updates correctly deployed
    + Node Cost in
  • Post Maintenance
    + Topology verification
    + Network state consistency check
Cause:
  • Time Consuming
  • Expensive
  • Error Prone
Network Change Automation
  • Time Effective
  • Low Cost
  • Error Free
Job Roles Are Shifting for Network Engineers:

Do Less of...
  • Device configurations
  • Continuous operations
  • Problem resolution
  • Hardware deployments
  • Monitoring and reporting
  • CLI entries and scripting
  • Hands-on repairs/deployments
Do More of...
  • Service innovation
  • Architectural (end-to-end) design
  • Network analytics & optimization
  • Programming - APIs versus CLI
  • Software administration
  • Comprehensive policy management
  • Systems integration/validation
Why Python For Network Engineering?

Is Python considered Easy? HUH?

MANY OF THE CONCEPTS ARE THE SAME BUT THE SYNTAX IS EASIER IN PYTHON

C++:
  • #include stdout

    int main()
    {
    std::count python
    Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> "hello world"
    'hello world'
    >>> exit()
    1. intro.py
    • print "hello world 2"
    C:python27>python intro.py
    hello world 2Integer & Float:
    Assigning Values to Variables:
    • counter = 100 # An integer assignment (10, 100, -786)
    • miles = 1000.0 # A floating point (0.0, 15.20, -21.9)
    • name = "John" # A string
    Single value to several variables:
    • a = b = c = 1
    Multiple objects to multiple variables:
    • a, b, c = 1, 2, "john"
    Delete reference to a number object:
    • del var
    • del var_a, var_b
    C:python27>python
    Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> counter = 100
    >>> counter
    100
    >>> anything=100
    >>> anything
    100
    >>> miles = 1000.5
    >>> miles
    1000.5
    >>> name = "John"
    >>> name
    'John'
    >>> name = 'John155'
    >>> name
    'John155'>>> a=b=c =1
    >>> a
    1
    >>> b
    1
    >>> c
    1
    >>> del a
    >>> a
    Traceback (most recent call last):
    File "", line 1, in
    NameError: name 'a' is not defined
    >>> del b
    >>> b
    Traceback (most recent call last):
    File "", line 1, in
    NameError: name 'b' is not defined
    >>> del c
    >>> c
    Traceback (most recent call last):
    File "", line 1, in
    NameError: name 'c' is not defined
    >>> a,b,c = 1,2.8,'Jhon'
    >>> a
    1
    >>> b
    2.8
    >>> c
    'Jhon'
    >>> exit()2. Ex.py
    • counter = 500
      miles = 2000.15
      name = 'Andrew'

      print counter
      print miles
      print name

      print counter, miles, name

      print 'The counter value is: ', counter
    C:python27>python Ex.py
    500
    2000.15
    Andrew
    500 2000.15 Andrew
    The counter value is: 500String:
    • str = 'Hello World!"
    • print str # Prints a complete string
    • print str[0] # Prints first character of the string
    • print str[2:5] # Prints characters starting from 3rd to 5th
    • print str[2:] # Prints string starting from 3rd character
    • print str * 2 # Prints string two times
    • print str + "TEST" # Prints concatenated string
    C:python27>python
    Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> a
    Traceback (most recent call last):
    File "", line 1, in
    NameError: name 'a' is not defined
    >>> a = 'Some text'
    >>> a = 'Chevy 427'
    >>> a
    'Chevy 427'
    >>> a = 'Hello'
    >>> b = 'World'
    >>> a
    'Hello'
    >>> b
    'World'
    >>> c = a + b
    >>> c
    'HelloWorld'
    >>> d = b + a
    >>> d
    'WorldHello'
    >>> 50 + 30
    80
    >>> '50'+'30'
    '5030'
    >>> str = "Hello World"
    >>> str
    'Hello World'
    >>> str[0]
    'H'
    >>> str[10]
    'd'
    >>> str[2:5]
    'llo'
    >>> str[2:8]
    'llo Wo'
    >>> str[:8]
    'Hello Wo'
    >>> str[2:]
    'llo World'
    >>> str[:]
    'Hello World'
    >>> str
    'Hello World'
    >>> new_string = "test "
    >>> new_string
    'test '
    >>> new_string * 4
    'test test test test '
    >>> new_string + new_string
    'test test '
    >>> str= new_string * 4
    >>> str
    'test test test test '
    >>> str= str + str
    >>> str
    'test test test test test test test test '3. Ex2.py
    • str = 'Hello World'
      print str

      first = str[:5]*4
      next = str[6:]*3

      print 'The first word is: ', first
      print 'The next word is: ', next
    C:python27>python Ex2.py
    Hello World
    The first word is: HelloHelloHelloHello
    The next word is: WorldWorldWorldLists:
    • list1 = ;
    • list2 = [1, 2, 3, 4, 5, 6, 7 ];
    • list3 = ["a", "b", "c", "d"];
    • print "list1[0]: ", list1[0]
    • print "list2[1:5]: ", list2[1:5]
    • print "Value available at index 2 : "
    • print list1[2]
    • list1[2] = 2001;
    • print "New value available at index 2 : "
    • print list1[2]
    • del list1[2];
    • print "After deleting value at index 2 : "
    • print list1
    len([1, 2, 3]) = 3 < Length
    [1, 2, 3] + [4, 5, 6] = [1, 2, 3, 4, 5, 6] < Concatenation * 4 = < Repetition
    cool.gif
 

PlAwAnSaI

Administrator
C:python27>python
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 =
>>> list1

>>> list1[1]
'chemistry'
>>> list1[1]='org chemistry'
>>> list1

>>> list2 = [1,2,3,4,5]
>>> list2
[1, 2, 3, 4, 5]
>>> list2*3
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> list3 =
>>> list3[2]
'h'
>>> newstr=list1[0]
>>> newstr
'physics'
>>> newstr[:4]
'phys'
>>> list1[3]=2001
>>> list1


4. Ex3.py
  • list1 =
    print 'list before update: ',list1
    list1[2] = 2000
    list1[3] = 2020
    print 'list after update: ',list1
C:python27>python Ex3.py
list before update:
list after update:

Tuple:
The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

  • tup1 = ('physics', 'chemistry', 1997, 2000);
  • tup2 = (1, 2, 3, 4, 5, 6, 7);
  • tup3 = "a", "b", "c", "d";
  • print "tup1[0]: ", tup1[0]
  • print "tup2[1:5]: ", tup2[1:5]
The empty tuple:
  • tup1 = ();
A tuple containing a single value:
  • tup1 = (50,);
Delete Tuple Elements:
  • del tuple;
>>> a = 1
>>> type(a)

>>> list1=
>>> list1

>>> type(list1)

>>> tup1=('phys','chem',1997,2001)
>>> tup1
('phys', 'chem', 1997, 2001)
>>> type(tup1)

>>> del list1
>>> list1
Traceback (most recent call last):
File "", line 1, in
NameError: name 'list1' is not defined
>>> list1=('phys','chem',1997,2001)
>>> type(list1)

>>> tup1[3]
2001
>>> tup1[3]=2020
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>> del tup1[3]
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object doesn't support item deletion
>>> list1=
>>> type(list1)

>>> list1[3]
2001
>>> list1[3]=2020
>>> list1

>>> del tup1
>>> tup1
Traceback (most recent call last):
File "", line 1, in
NameError: name 'tup1' is not defined

Dictionary:
  • dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
  • print "dict: ", dict
Updating Dictionary
  • dict = 8; # update existing entry
  • dict = "DPS School"; # Add new entry
>>> dict = {'Name' : 'Zara','Age' : 7, 'Class' : 'first'}
>>> type(dict)

>>> list1 = {'Name' : 'Zara','Age' : 7, 'Class' : 'first'}
>>> type(list1)

>>> dict
{'Age': 7, 'Name': 'Zara', 'Class': 'first'}
>>> dict
7
>>> dict
Traceback (most recent call last):
File "", line 1, in
KeyError: 'age'
>>> dict=10
>>> dict
{'Age': 10, 'Name': 'Zara', 'Class': 'first'}
>>> dict = 'Fifth'
>>> dict
{'Age': 10, 'Name': 'Zara', 'Class': 'Fifth'}
>>> del dict
>>> dict
{'Age': 10, 'Name': 'Zara'}
  • Suppose list1 is [3, 5, 25, 1, 3], min(list1) is 1.
    min returns the minimum element in the list.
  • Use function random.shuffle(list1) to shuffle the list(say list1).
  • Suppose list1 is [1, 5, 9, sum(list1) is 15.
    Sum returns the sum of all elements in the list.
  • A class is a user-defined datatype, not a core datatype.
  • L = [1, 23, 'hello', 1], datatype is List.
    List datatype can store any values within it.
Loop:
  • for iterating_var in sequence:
  • statement(s)
  • for letter in 'Python':
  • print 'Current Letter :', letter
  • fruits =
  • for fruit in fruits:
  • print 'Current fruit :', fruit
5. forloops.py
  • fruits =

    for i in fruits:
    print 'Current the fruit is ', i
    print 'Goodbye'
    print 'type = ', type(i)

    for letter in 'Python':
    print 'Current Letter = ', letter
    print 'Goodbye'
C:python27>python forloops.py
Current the fruit is banana
Goodbye
Current the fruit is apple
Goodbye
Current the fruit is mango
Goodbye
Current the fruit is orange
Goodbye
Current the fruit is berry
Goodbye
type =
Current Letter = P
Current Letter = y
Current Letter = t
Current Letter = h
Current Letter = o
Current Letter = n
Goodbye
  • while expression:
  • statement(s)
  • count = 0
  • while (count < 9):
  • print 'The count is:', count
  • count = count + 1
  • print "Goodbye!"
6. Whileloops.py
  • count = 0
    while (count < 9):
    print 'The count is:', count
    count = count + 1
    print "Loop has done!"
C:python27>python Whileloops.py
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Loop has done!
  • for iterating_var in sequence:
  • for iterating_var in sequence:
  • statements(s)
  • statements(s)
  • while expression:
  • while expression:
  • statement(s)
  • statement(s)
7. nest.py
  • for i in range(1,5):
    for j in range(1,3):
    print "j=",j
    print " *i=",i
    print "loops done"
C:python27>python nest.py
j= 1
j= 2
*i= 1
j= 1
j= 2
*i= 2
j= 1
j= 2
*i= 3
j= 1
j= 2
*i= 4
loops done
  • x =
    for i in x:
    i.upper()
    print(x)
    Output:
    The function upper() does not modify a string in place, it returns a new string which isn't being stored anywhere.
  • i=1
    while True:
    if i%007 == 0:
    break
    print(i)
    i += 1
    Output: 1 2 3 4 5 6
cool.gif
 

PlAwAnSaI

Administrator
Control:
  • if expression:
  • statement(s)
  • var1 = 100
  • if var1:
  • print "1 - Got a true expression value"
  • print var1
  • var2 = 0
  • if var2:
  • print "2 - Got a true expression value"
  • print var2
  • print "Good bye!"
8. if.py
  • var1 = 'area'
    if var1 == 'area':
    print 'Area = length * width'

    var1 = 'volume'
    if var1 == 'volume':
    print 'Volume = length & width * height'

    var1 = 100
    if var1:
    print "1 - true"
    print var1

    var2 = 0
    if var2:
    print '2 - true'
    print var2

    var3 = 'a'
    if var3:
    print "3 - true"
    print var3

    var4 = ''
    if var4:
    print "4 - true"
    print var4
C:python27>python if.py
Area = length * width
Volume = length & width * height
1 - true
100
3 - true
a
  • if expression:
  • statement(s)
  • else
  • statement(s)
9. ifelse.py
  • var1= 100
    if var1:
    print ' 1 - true'
    print var1
    else:
    print ' 1 - false'

    var2 = 0
    if var2:
    print '2 - got true'
    print var2
    else:
    print '2 - got false'
    print var2

    print 'goodbye'
C:python27>python ifelse.py
1 - true
100
2 - got false
0
goodbye
  • if expression1:
  • statement(s)
  • elif expression2:
  • statement(s)
  • elif expression3:
  • statement(s)
  • else:
  • statement(s)
10. ifelif.py
  • var = 100
    if var == 100:
    print '1 got true'
    print var

    elif var == 150:
    print '2 got true'
    print var

    elif var == 100:
    print '3 got true'
    print var

    else:
    print '4 got false'
    print var

    print 'goodbye'
C:python27>python ifelif.py
1 got true
100
goodbyeOperators:
>>> a=10
>>> b=20
>>> a+b
30
>>> a-b
-10
>>> a*b
200
>>> b/a
2
>>> b%a => Modulus: / but returns remainder
0
>>> b=23
>>> b%a
3
>>> a=4
>>> b=3
>>> a**b => a^b
64
>>> 9//2 => / but the digits after the decimal point are removed
4
>>> 8//2
4
>>> 8.5//2
4.0
>>> 8.5/2
4.2511. operators.py
  • a = 100
    b = 100
    if (a == b):
    print 'True'
    print 'a =', a, '== b =', b
    print ''

    a = 10
    if (a != b):
    print 'True'
    print 'a =', a, '!= b =', b
    print ''

    a = 100
    if (a b):
    print 'True'
    print 'a =', a, 'b =', b
    else:
    print 'False - '
    print 'a =', a, 'b =', b
    print ''

    b = 10
    if (a > b):
    print 'True'
    print 'a =', a, '> b =', b
    print ''

    if (a < b):
    print 'True'
    print 'a =', a, 'b =', b
    else:
    print 'False - = b =', b
    print ''

    b = 100
    if (a python operators.py
    True
    a = 100 == b = 100

    True
    a = 10 != b = 100

    False -
    a = 100 b = 100

    True
    a = 100 > b = 10

    False - <
    a = 100 b = 10

    False - = b = 10

    True
    a = 100 python andor.py
    True
    a = 1 and b = 1000

    True
    a = 0 or b = 1000

    True
    not(a = 0 and b = 1000 )
    endFunction:
    • def functionname( parameters ):
    • "function_docstring"
    • function_suite
    • return [expression]
    13. funexamp.py
    • # Function definition is here
      def print_me( str ):
      "This prints a passed string into this function"
      print str
      return;

      # Now you can call print_me function
      print_me("I'm the first call to user defined function!")

      a="Again second call to the same function"
      print_me(a)

      print 'stop'
    C:python27>python funexamp.py
    I'm the first call to user defined function!
    Again second call to the same function
    stop14. funexamp2.py
    • # Function definition is here
      def change_me( my_list ):
      "This changes a passed list into this function"
      my_list.append([1,2,3,4]);
      return;

      # Now you can call change_me function
      my_list = [10,20,30];
      change_me( my_list);
      print "Values the function: ", my_list
    C:python27>python funexamp2.py
    Values the function: [10, 20, 30, [1, 2, 3, 4]]Project 1: Change ProgramYou are creating software to be sold by your company to vending machine manufacturers to count and return change. You are part of a Team, more code may be required to complete the obligations to the customer but you have been given the following assignment
    • Items in the vending machine have a cost value between .01 - .99
    • You will use a Randomly generated value from .01 to .99 to simulate the cost of possible vending items.
    • The customer chooses an item and enters some coins, the machine's electronics determine the coins to be either (Customer enters coins)
    v7YEry.jpg

    15. proj1.py
    Input coins:
    • quarter=25
      dime = 10
      nickel = 5
      penny = 1
      item_cost = 54

      print 'This item costs ', item_cost
      print ('**Enter coins in form 1,5,10,25,..')

      coin_value = input('enter coin values')

      print coin_value
    C:python27>python proj1.py
    This item costs 54
    **Enter coins in form 1,5,10,25,..
    enter coin values 1,5,10,25,1,1,10
    (1, 5, 10, 25, 1, 1, 10)

    C:python27>python proj1.py
    This item costs 54
    **Enter coins in form 1,5,10,25,..
    enter coin values 1,5,10,25,1,1,10,12,17
    (1, 5, 10, 25, 1, 1, 10, 12, 17)
    cool.gif
 

PlAwAnSaI

Administrator
Invalid Coins:
  • num_coins = len(coin_value)
    print coin_value, num_coins
    count = 0

    while count < num_coins: # step each look for invalid
    current_value = coin_value[count]
    coin_amt = int(current_value)
    print 'count = ', count, 'Coin Amount = ', coin_amt
    count += 1
    if coin_amt not in (quarter, dime, nickel, penny):
    print 'An Invalid coin was detected'
    count = 0
    coin_value = 0
    num_coins = 0
    coin_amt = 0
    coin_value = input('enter coin values')
    num_coins = len(coin_value)
C:python27>python proj1.py
This item costs 54
**Enter coins in form 1,5,10,25,..
enter coin values 5,5,1,1,12,10
(5, 5, 1, 1, 12, 10) 6
count = 0 Coin Amount = 5
count = 1 Coin Amount = 5
count = 2 Coin Amount = 1
count = 3 Coin Amount = 1
count = 4 Coin Amount = 12
An Invalid coin was detected
enter coin values 5,5,1,1,10
count = 0 Coin Amount = 5
count = 1 Coin Amount = 5
count = 2 Coin Amount = 1
count = 3 Coin Amount = 1
count = 4 Coin Amount = 10Coin Count:
  • total_quarters = 0 #This is setting coin count to zero only
    total_dimes = 0
    total_nickels = 0
    total_pennies = 0

    print coin_value, num_coins

    while count < num_coins: # step each look for invalid
    current_value = coin_value[count]
    coin_amt = int(current_value)
    print 'count = ', count, 'Coin Amount = ', coin_amt
    count += 1

    if coin_amt not in (quarter, dime, nickel, penny):
    print 'An Invalid coin was detected'
    count = 0
    coin_value = 0
    num_coins = 0
    coin_amt = 0

    total_quarters = 0 #This is setting coin count to zero only
    total_dimes = 0 #need to deduct the coins returned
    total_nickels = 0 #need to fix this.
    total_pennies = 0

    coin_value = input('enter coin values ')
    num_coins = len(coin_value)

    elif coin_amt == 25:
    total_quarters += 1
    elif coin_amt == 10:
    total_dimes += 1
    elif coin_amt == 5:
    total_nickels += 1
    elif coin_amt == 1:
    total_pennies += 1

    coin_count = (total_quarters, total_dimes, total_nickels, total_pennies)
    total_value = total_quarters * 25 + total_dimes * 10 + total_nickels * 5 + total_pennies

    print 'Coin count = q,d,n,p ' ,coin_count
    print 'Total value =',total_value
C:python27>python proj1.py
This item costs 54
**Enter coins in form 1,5,10,25,..
enter coin values 5,10,5,10
(5, 10, 5, 10) 4
count = 0 Coin Amount = 5
count = 1 Coin Amount = 10
count = 2 Coin Amount = 5
count = 3 Coin Amount = 10
Coin count = q,d,n,p (0, 2, 2, 0)
Total value = 30Make a decision:
  • done = 0

    while done == 0:
    while count < num_coins: # step each look for invalid
    current_value = coin_value[count]
    coin_amt = int(current_value)
    print 'count = ', count, 'Coin Amount = ', coin_amt
    count += 1
    if coin_amt not in (quarter, dime, nickel, penny):
    ...
    print 'Total value =',total_value

    # 3 conditions

    if item_cost == total_value:
    # done
    print 'Thank you please take your item'
    done = 1
    elif item_cost < total_value:
    # return change
    return_change = total_value - item_cost
    # *update coin count*
    print 'Please take your change of ',return_change
    print 'Still need to update coin count'
    done = 1
    elif item_cost > total_value:
    # input more coins
    item_cost = item_cost - total_value
    # *Do everything over until done*
    print 'Not enough money please enter ',item_cost
    count = 0
    coin_value = 0
    num_coins = 0
    coin_amt = 0
    total_quarters = 0 # fix this total as well
    total_dimes = 0
    total_nickels = 0
    total_pennies = 0
    coin_value = input('enter coin values')
    num_coins = len(coin_value)
C:python27>python proj1.py
This item costs 54
**Enter coins in form 1,5,10,25,..
enter coin values 25,25,1,1,1,1
(25, 25, 1, 1, 1, 1) 6
count = 0 Coin Amount = 25
count = 1 Coin Amount = 25
count = 2 Coin Amount = 1
count = 3 Coin Amount = 1
count = 4 Coin Amount = 1
count = 5 Coin Amount = 1
Coin count = q,d,n,p (2, 0, 0, 4)
Total value = 54
Thank you please take your item

C:python27>python proj1.py
This item costs 54
**Enter coins in form 1,5,10,25,..
enter coin values 25,25,10
(25, 25, 10) 3
count = 0 Coin Amount = 25
count = 1 Coin Amount = 25
count = 2 Coin Amount = 10
Coin count = q,d,n,p (2, 1, 0, 0)
Total value = 60
Please take your change of 6
Still need to update coin count

C:python27>python proj1.py
This item costs 54
**Enter coins in form 1,5,10,25,..
enter coin values 25,25
(25, 25) 2
count = 0 Coin Amount = 25
count = 1 Coin Amount = 25
Coin count = q,d,n,p (2, 0, 0, 0)
Total value = 50
Not enough money please enter 4
enter coin values 1,1,1,1
count = 0 Coin Amount = 1
count = 1 Coin Amount = 1
count = 2 Coin Amount = 1
count = 3 Coin Amount = 1
Coin count = q,d,n,p (0, 0, 0, 4)
Total value = 4
Thank you please take your item
cool.gif
 

PlAwAnSaI

Administrator
16. proj1_g2.py
  • upload.i4th.in.th:8080/th/download.php?id=593CE4151
Case: 1st, Condition: Exact Change, Change in: 2 quarters, Total coins: (2,0,0,0), Total Value: 50, Action: Take ItemC:python27>python proj1_g2.py

*************New Purchase****************
This item costs 50
**Enter coins in form 1,5,10,25,..
25,25
(25, 25) 2
Is machine Being Serviced?
0 for no or 1 for yes
0
Checking for invalid coins
Checking for invalid coins
Thank you please take your item
Coin count= q,d,n,p (2, 0, 0, 0)
Total value= 50
***********End of Purchase****************Case: 2nd, Condition: Exact Change, Change in: 5 dimes, Total coins: (2,5,0,0), Total Value: 100, Action: Take Item
*************New Purchase****************
This item costs 50
**Enter coins in form 1,5,10,25,..
10,10,10,10,10
(10, 10, 10, 10, 10) 5
Is machine Being Serviced?
0 for no or 1 for yes
0
Checking for invalid coins
Checking for invalid coins
Checking for invalid coins
Checking for invalid coins
Checking for invalid coins
Thank you please take your item
Coin count= q,d,n,p (2, 5, 0, 0)
Total value= 100
***********End of Purchase****************

Case: 3rd, Condition: Too Much, Change in: 2 quarters 2 dimes, Total coins: (4,5,0,0), Total Value: 150, Action: Return change

*************New Purchase****************
This item costs 50
**Enter coins in form 1,5,10,25,..
25,25,10,10
(25, 25, 10, 10) 4
Is machine Being Serviced?
0 for no or 1 for yes
0
Checking for invalid coins
Checking for invalid coins
Checking for invalid coins
Checking for invalid coins
Return Change (0, 2, 0, 0)
updated coin totals = q,d,n,p (4, 5, 0, 0)
Thank you please take your item
Coin count= q,d,n,p (4, 5, 0, 0)
Total value= 150
***********End of Purchase****************

Case: 4th, Condition: Not enough, Change in: 1 quarters 1 nickle, Total coins: (5,5,1,0), Total Value: 180, Action: Enter difference

*************New Purchase****************
This item costs 50
**Enter coins in form 1,5,10,25,..
25,5
(25, 5) 2
Is machine Being Serviced?
0 for no or 1 for yes
0
Checking for invalid coins
Checking for invalid coins
Not enough money please enter 20
Coin count= q,d,n,p (5, 5, 1, 0)
Total value= 180
enter coin values 10,5,5


Checking for invalid coins
Checking for invalid coins
Checking for invalid coins
Thank you please take your item
Coin count= q,d,n,p (5, 6, 3, 0)
Total value= 200
***********End of Purchase****************

Case: 5th, Condition: Invalid Coin, Change in: 10,40, Total coins: (5,6,3,0), Total Value: 200, Action: return coin

*************New Purchase****************
This item costs 50
**Enter coins in form 1,5,10,25,..
10,40
(10, 40) 2
Is machine Being Serviced?
0 for no or 1 for yes
0
Checking for invalid coins
Checking for invalid coins
An Invalid coin was detected please take change
Coin count is (5, 6, 3, 0)
enter coin values 25,25
Checking for invalid coins
Checking for invalid coins
Thank you please take your item
Coin count= q,d,n,p (7, 6, 3, 0)
Total value= 250
***********End of Purchase****************

gns3.com

17. func.py
  • #Procedure 1
    def main():
    try:
    # Get a number to manipulate
    num = float(input("Please enter a number to manipulate.n"))
    # Store the result of the value, after it has been manipulated
    # by Procedure 2
    addednum = addfive(num)
    # Store the result of the value, after it has been manipulated
    # by Procedure 3
    multipliednum = multiply(addednum)
    # Send the value to Procedure 4
    display(multipliednum)
    # Deal with exceptions from non-numeric user entry
    except ValueError:
    print("You must enter a valid number.n")
    # Reset the value of num, to clear non-numeric data.
    num = 0
    # Call main, again.
    main()

    # Procedure 2
    def addfive(num):
    return num + 5

    # Procedure 3
    def multiply(addednum):
    return addednum * 2

    # Procedure 4
    def display(multi):
    # Display the final value
    print("The final value is ",multi)

    # Call Procedure 1
    main()
C:python27>python func.py
Please enter a number to manipulate.
'k'
You must enter a valid number.

Please enter a number to manipulate.
2
('The final value is ', 14.0)18. class1.py
  • class Numchange:

    def _int_(self):
    self._number = 0
    def addfive(self,num):
    self._number = num
    return self._number + 5

    def multiply(self,added):
    self._added = added
    return self._added * 2
19. op1.py
  • import class1

    maths = class1.Numchange()

    def main():

    num = float(input("Please enter a number.n"))

    added = maths.addfive(num)

    multip = maths.multiply(added)

    print("The manipulated value is ", multip)

    main()
C:python27>python op1.py
Please enter a number.
2
('The manipulated value is ', 14.0)
  • Functions are reusable pieces of the program. They allow you to give a name to a block of statements, allowing you to run that block using the specified name anywhere in your program and any number of times.
  • Def is a keyword used for function.
  • def sayHello():
    print('Hello World!')
    sayHello()
    sayHello()

    Output: Hello World! Hello World!

    Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed by a pair of parentheses which may enclose some names of variables, and by the final colon that ends the line. Next follows the block of statements that are part of this function.
cool.gif
 

PlAwAnSaI

Administrator
20. TN3.py
  • import telnetlib
    import time

    def telnet_gns3(ip):
    wait = .2

    connection = telnetlib.Telnet(ip, 23, 5)

    output = connection.read_until("Password:", 5)
    connection.write('cisco' + "n")
    connection.write('ena' + "n")

    output = connection.read_until("Password:", 5)
    connection.write('cisco' + "n")
    time.sleep(wait)

    connection.write("conf term" + "n")
    time.sleep(wait)
    connection.write("int f0/0" + "n")
    time.sleep(wait)
    connection.write("ip add 6.5.5.5 255.0.0.0" + "n")
    time.sleep(wait)
    connection.write("end" + "n")

    time.sleep(wait)
    connection.write("sho ip int brief" + "n")
    time.sleep(wait)

    output = connection.read_very_eager()
    print output

    connection.close()

    #Call gns3
    telnet_gns3('192.168.56.101')
C:python27>python TN3.py

ESW1#conf term
Enter configuration commands, one per line. End with CNTL/Z.
ESW1(config)#int f0/0
ESW1(config-if)#ip add 6.5.5.5 255.0.0.0
ESW1(config-if)#end
ESW1#sho ip int brief
Interface IP-Address OK? Method Status Protocol
FastEthernet0/0 6.5.5.5 YES manual administratively down down
FastEthernet0/1 192.168.56.101 YES manual up up
FastEthernet1/0 unassigned YES unset up down
FastEthernet1/1 unassigned YES unset up down
FastEthernet1/2 unassigned YES unset up down
FastEthernet1/3 unassigned YES unset up down
FastEthernet1/4 unassigned YES unset up down
FastEthernet1/5 unassigned YES unset up down
FastEthernet1/6 unassigned YES unset up down
FastEthernet1/7 unassigned YES unset up down
FastEthernet1/8 unassigned YES unset up down
--More--

21. TN4.py
  • ...
    output = connection.read_very_eager()
    # - Write output to a file -
    ESW1 = open("ESW1", "w")
    ESW1.write(output)
    ESW1.close
    print output
    ...
upload.i4th.in.th/th/download.php?id=59493B94122. TN7.py
  • import telnetlib
    import time

    def telnet_gns3(ip):
    wait = 5
    # -Sign in-
    connection = telnetlib.Telnet(ip, 23, 5)
    connection.read_until("Password:", 5)
    connection.write('cisco' + "n")
    connection.write('ena' + "n")
    connection.read_until("Password:", 5)
    connection.write('cisco' + "n")
    # -Sign in-

    # -Command loop-
    cmd_file = raw_input('Enter command file name and extension: ')
    selected_cmd_file = open(cmd_file, 'r')
    selected_cmd_file.seek(0)
    for each_line in selected_cmd_file.readlines():
    time.sleep(wait)
    connection.write(each_line)
    connection.write("n")
    # -Command loop-

    # -Write output to a file-
    time.sleep(wait)
    output = connection.read_very_eager()
    ESW1 = open("ESW1", "w")
    ESW1.write(output)
    ESW1.close
    # -Write output to a file-
    print output

    connection.close()

    #Call gns3
    telnet_gns3('192.168.56.101')
testcmds.txt
  • conf term
    int f0/0
    ip add 5.5.5.5 255.0.0.0
    end
    sho ip int brief
    sho run
C:python27>python TN7.py
Enter command file name and extension: testcmds.txt

ESW1#conf term
Enter configuration commands, one per line. End with CNTL/Z.
ESW1(config)#
ESW1(config)#int f0/0
ESW1(config-if)#
ESW1(config-if)#ip add 5.5.5.5 255.0.0.0
ESW1(config-if)#
ESW1(config-if)#end
ESW1#
ESW1#sho ip int brief
Interface IP-Address OK? Method Status Protocol
FastEthernet0/0 5.5.5.5 YES manual administratively down down
FastEthernet0/1 192.168.56.101 YES manual up up
...
upload.i4th.in.th/th/download.php?id=594E30291
cool.gif
 

PlAwAnSaI

Administrator
Is the CCIE Dead? The Automated Future of IT

Drive For Show And Putt For Dough - ลูกไดรฟ์มีไว้อวด ลูกพัตต์มีไว้เอาเงิน

GUI For Show And API For Dough

Why API?
  • Automation
  • Integration
  • Innovation
What about networking skills?
  • "A fool with a tool is still a fool"
23. TN20.py
  • upload.i4th.in.th/th/download.php?id=59A27D191
C:python27>python TN20.py
Enter command file name and extension: ESW1cmds.txt
Enter command file name and extension: ESW2cmds.txt
Enter command file name and extension: ESW3cmds.txt
Enter command file name and extension: ESW4cmds.txtIOS Telnet Configuration:
  • ena sec cisco
    !
    line vty 0 4
    exec-timeout 5 0
    password cisco
    login
Telnet to n Number of Routers:
  • get the value:
    >>> ip = '192.168.1.101'
    >>> ip
    '192.168.1.101'
    >>> len(ip)-1
    12
    >>> last_char = len(ip)-1
    >>> last_char
    12
    >>> ip[last_char]
    '1'

    >>> ip[10:13]
    '101'
    >>> quad = ip[len(ip)-3:len(ip)]
    >>> quad
    '101'
    >>> type(quad)

  • convert to int:
    >>> int(ip[last_char])
    1
    >>> current_int = int(ip[last_char])

    >>> int(quad)
    101
    >>> quad_int = int(quad)
    >>> quad_int
    101
  • add 1:
    >>> current_int = current_int + 1
    >>> current_int
    2

    >>> quad_int = quad_int + 1
    >>> quad_int
    102
  • convert to string:
    >>> quads = str(quad_int)
    >>> quads
    '102'
  • ip # with the new:
    >>> temp_ip = ip[:len(ip)-3]
    >>> temp_ip
    '192.168.1.'
    >>> ip = temp_ip + quads
    >>> ip
    '192.168.1.102'
  • increment through for n number of routers
24. TN24.py
  • ip = '192.168.1.101'
    n = 27
    #start loop
    for router in range(1,n):
    print(router,ip)
    quad = ip[len(ip)-3:len(ip)]
    quad_int = int(quad)
    quad_int = quad_int + 1
    quads = str(quad_int)
    temp_ip = ip[:len(ip)-3] # strings immutable
    ip = temp_ip + quads
C:python27>python TN24.py
(1, '192.168.1.101')
(2, '192.168.1.102')
...
(26, '192.168.1.126')25. TN25.py
  • change TN20.py since:
    #loop n number times where n = the number of routers
    ip = '192.168.56.101'
    n = 3
    #start loop
    for router in range(1,n):
    telnet_gns3(ip,router)
    print(router,ip)
    quad = ip[len(ip)-3:len(ip)]
    quad_int = int(quad)
    quad_int = quad_int + 1
    quads = str(quad_int)
    temp_ip = ip[:len(ip)-3] # strings immutable
    ip = temp_ip + quads
C:python27>python TN25.py
Enter command file name and extension: ESW1cmds.txt
(1, '192.168.56.101')
Enter command file name and extension: ESW2cmds.txt
(2, '192.168.56.102')26. TN1000.py
  • ...
    # -Write output to a file-
    ESW =
    time.sleep(wait)
    output = connection.read_very_eager()
    ESW[router] = open("ESW" + str(router), "w")
    ESW[router].write(output)
    ESW[router].close
    # -Write output to a file-
    ...
27. TN1001.py
  • ...
    # -Write output to a file-
    time.sleep(wait)
    output = connection.read_very_eager()
    ESWtemp = open("ESW" + str(router), "w")
    ESWtemp.write(output)
    ESWtemp.close
    # -Write output to a file-
    ...
>>> ip = '192.168.1.101'
>>> ip
'192.168.1.101'
>>> p3 = ip.rfind('.')
>>> p3
9
>>> temp_s = ip[:p3+1]
>>> temp_s
'192.168.1.'
>>> quad = ip[p3+1:]
>>> quad
'101'
>>> quad_int = int(quad)
>>> quad_int
101
>>> type(quad_int)
28. TN1003.py
  • ip = '1.1.12.5'
    p3 = ip.rfind('.')
    temp_s = ip[:p3+1]
    quad = ip[p3+1:]
    quad_int = int(quad)

    n = 10
    #start loop
    for router in range(1,n):
    print(router,ip)
    quad_int = quad_int + 1
    quads = str(quad_int)
    ip = temp_s + quads
C:python27>python TN1003.py
(1, '1.1.12.5')
(2, '1.1.12.6')
(3, '1.1.12.7')
(4, '1.1.12.8')
(5, '1.1.12.9')
(6, '1.1.12.10')
(7, '1.1.12.11')
(8, '1.1.12.12')
(9, '1.1.12.13')Change ESW1 & ESW2 Management IP to 192.168.x.99 - 100 respectively29. TN2000.py
  • change TN1001.py by TN1003 since:
    #loop n number times where n = the number of routers
    ip = '192.168.56.99'

    p3 = ip.rfind('.')
    temp_s = ip[:p3+1]
    quad = ip[p3+1:]
    quad_int = int(quad)

    n = 3
    #start loop
    for router in range(1,n):
    telnet_gns3(ip,router)
    print(router,ip)
    quad_int = quad_int + 1
    quads = str(quad_int)
    ip = temp_s + quads
C:python27>python TN2000.py
Enter command file name and extension: ESW1cmds.txt
(1, '192.168.56.99')
Enter command file name and extension: ESW2cmds.txt
(2, '192.168.56.100')Program Your Career. Learn Network Programmability:Network Engineer Job Role Evolution:Digitization Is Changing The World:
  • Bookstore
  • Taxi
  • Music
  • Hotel
  • Print Advertising
  • Car
  • Point-of-Sale
CEO Technology Investment Priorities: 2014/15: Most Important Technology-Enabled Capability Investments Over the Next Five Years
  • Digital marketing 38%
  • E-commerce 34%
  • Customer experience management 34%
  • Business analytics 32%
  • Cloud business 27%
  • ...
  • Additive manufacturing 4%
  • Gamification 4%
  • Robot staffing 4%
  • Neurobusiness 2%
  • Salesforce automation 1%
www.gartner.com/doc/2704918/gartner-ceo-senior-executive-survey
www.gartner.com/smarterwithgartner/2017-ceo-survey-infographicEmerging Jobs of the Future: College students are studying to prepare for jobs that do not exist... yet
  • Business Transformation Architect
  • Cloud Architects/Brokers
  • Customer Outcome Evangelist
  • Cyber Security Specialist
  • Data Scientist
  • Innovation Specialist
  • Mobile Application Developer
  • Network Programmer
  • Process Control Engineer
  • Social Scientists
www.itcareerfinder.com/brain-food/blog/entry/best-computer-jobs-for-the-future.htmlwww.infoworld.com/article/3160526/application-development/infoworlds-2017-technology-of-the-year-award-winners.htmlwww.networkworld.com/article/3158845/lan-wan/software-may-be-eating-the-world-but-cumulus-networks-is-still-keen-on-hardware.html
cool.gif
 

PlAwAnSaI

Administrator
The Network at the Center of Every Evolution Step: Managing Your Career Through Key Market TransitionsIndustry Relevant Bridge the Knowledge GapsCentralized > Silo'd > Unconnected > Network as Platform > Internet of Everything
  • Growing IT Talent Gaps
  • Re-skilling Needed
  • Evolving Job Roles By Industry
  • Programmability Skills Required
  • Business Skills In Demand
  • Business requirements for globalization, flexibility, speed
  • Line of Business involvement in IT spending
  • Consumerization of IT - software-based services
  • Disruptive technologies: cloud, mobility, social, video, Big Data
Networker Responsibilities are Growing and Shifting:Responsibility Focus:
  • Increase of Design
  • Decrease of Deploy
  • Decrease of Operate
  • Increase of Optimize
  • Innovate
  • WAN, WLAN, Routers, Switches, UC, L4-7
  • Compute/Storage, Security, NFV, Orchestrators, Controllers, Hypervisors, Analytics, Automation, Transformation
Network Programmability in a Programmable Networking Environment:
08J6WQ.jpg


What is Network Programmability?

Network Provisioning...:
App Developer - Application Tiers, Provider / Consumer Relationship -> NW Architect - Security Policy, QoS Policy, Other Policies -> NW Engineer - SSH -> Devices

Network Programmability...:
App Developer - Application Tiers, Provider / Consumer Relationship -> NW Architect - Security Policy, QoS Policy, Other Policies -> NW Engineer - Policy Construct -> APIC - Instantiate Policy -> Devices

Policy Construct:

Event Triggers -

  • Network Users:
    • User-identifier (tenant/user)
    • Application
    • Location Device Type
  • Policy Properties:
    • Policy Creator
    • Policy Name
    • Policy Scope
    • Policy Priority
    • Policy Time:
      • Start Time
      • End Time
      • Hard timeout
      • Idle timeout
      • recurrence
  • Resources:
    • User-identifier (tenant/user)
    • Application
    • Device Type
    • Location
  • Actions:
    • Permit
    • Deny
    • Copy
    • Monitor
    • Redirect (L3, L4, L7)
    • No copy
    • No redirect
  • Action Properties:
    • Priority Level
    • Resource Level
    • Experience Level
    • Trust Level
    • Destination
    • Sample Rate
  • High-Level Business Intent Policies
  • Automatically converted to Network Language
  • Conflict Detection and Resolution
  • Extensible
  • Supports different patterns of policies:
    • Access Policies
    • Source-Destination Directional Policies
    • Event - Condition - Action
    • Includes Collections (Ex: a group of user ids, a group of applications, etc.)
    • Choose custom tags for policies
    • Choose multiple attributes in each category
Abstracting Conventional Policy Complexity:
  • Conventional Model:
    Admin Driven [
    • The What "Security Policy for Branch A"
    • The How "Change ACLs in the Following Elements" ->
  • ACI Policy Model:
    • The What "Security Policy" - Admin Driven
    • ACI Constructs - Northbound APIs
    • The How "Change ACLs in the Following Elements" - APIC EM ]
ACI Abstracts System Management and Enables Programmable Driven PoliciesMove from micro-managing "boxes" to a policy-driven, holistic view of the networkProactive Network Applications: Automate Network ProvisioningKey Use Cases:
  • Agile Network Provisioning
  • Device Health Monitoring
  • Auditing/Compliance
Key Skills:
  • REST
  • NETCONF/YANG
  • Puppet/Chef (DC)
  • C, JAVA, Python
dNP9LB.jpg

Modify QoS policies across the network based on services ordered by the end customer. Ex: VOIP call or stream video

Monitor the network to assure SLA. Enables SPs to offer differentiated services to their end customers

Reactive Network Applications: Dynamically Interact with the Network

Key Use Cases:
  • Security
  • Dynamic QoS
  • Traffic Steering
Key Skills:
  • C, JAVA, or Python
  • REST
ZolZ9P.jpg

Crossing The Chasm: There is a lot we could learn from each other if we can cross the chasm
  • CLI config
  • Scalability
  • Resiliency
  • Stability
  • Availability
  • Stuck in the DC
  • Code
  • Agility
  • Automation
  • Testing
  • Advanced Tools
  • Coding where you like
Development Economics - Deploying a physical network test-bed requires:
  • Equipment about $2,000/node
  • Setup about 1-2 hours per network
  • Expertise level high @ about $100/hour for CCNA
  • Resources must be dedicated, scheduled
Time and money you probably don't haveVIRL can help simplify and streamline development processes and environmentsWhat is VIRL? - A network orchestration and virtualization platform that enables:
  • Point-and-click network design
  • Painless configuration
  • Integration of platform-sync'd code
  • Rapid setup and tear-down
  • Seamless connectivity with 'real' networks
  • Portability and repeatability
Virtualized Network Operating Systems:
  • IOS-XRv: IOS XR v5.1.3 and v5.2.0
  • NX-OSv: NX-OS v7.1(0)ZD
  • CSR1000v: IOS XE v15.4(3S_XE313)
  • IOSv: IOS v15.4(1.20T)
  • Servers: Ubuntu 14.04 LTS
The Wall of Confusion: Or, why can't we all just get on together?
  • Development: I want to change!
  • Operations: I want stability!
DevOps Virtuous Cycle:
  • Increased Reliability
  • Higher Quality
  • Improved Maintain-ability
  • Faster Releases
  • Increased Innovation
  • Improved Scalability
  • Increased Proactivity
Aspects of DevOps - Agile Development and CI/CD:Continuous Integration and Deployment in the Development Cycle:
  • Build Automation
  • Virtual Environments
  • Reporting and Visibility
  • Artefact Management
  • Coding and Refactoring
  • Source Code Management
Introducing DevNet: Creating a Community of Software Developers who Leverage Cisco Technology in Their WorkEnabling a Robust Developer Ecosystem:
  • Engineering Platform APIs
  • SDKs and Tools
  • Developer Support
  • Community Management
To Build Compelling and Innovative Apps
  • Developer.Cisco.Com
  • devnetsandbox.cisco.com/RM/Topology
Network Architecture: The Design
https://www.youtube.com/watch?v=TzGpNEfvMC8
cool.gif
 

PlAwAnSaI

Administrator
Network Programmability Certifications:Evolution of Major IT Roles in the IT DevOps World: Orchestrating for OutcomesBefore > After
  • Analyst:
    • Business support > Business transformation
    • Systems efficiency > System analysis
    • Infrastructure protection > Process optimization
  • Architect:
    • IT segment design > Enterprise system view
    • Technology-driven > Business-driven
    • Resource avail/access > Resource optimization
  • App Developer:
    • Single work function view > Business workflow view
    • Delivery focus > Outcome focus
    • Network agnostic > Network aware
  • Administrator:
    • Silo view > Holistic system view
    • Hardware-centric > Software-centric
    • Deploy and operate > Innovate and optimize
Network Programmability Industry Job Roles Evolution and Certifications:Traditional Networking Infrastructure > Network Programmability Roles > Network Programmability Certifications and Curriculum
  • Business App Engineer > Business Application Engineer - network Programmability aware > 2 exams
  • New > Network Programmability Developer > CCNA + 2 exams
  • System Engineer/Network Designer > Network Programmability Designer > CCNP + 2 exams
  • Network Engineer/Support Engineer > Network Programmability Engineer > CCNP + 2 exams
  • Is the CCIE still Valuable in 2017?
    nhprice.com/the-value-of-ccie.html
  • Software-defined networks (SDN): an architectural approach that optimizes and simplifies network operations by more closely binding the interaction (i.e., provisioning, messaging, and alarming) among applications and network services and devices, whether they be real or virtualized. It often is achieved by employing a point of logically centralized network control - which is often realized as an SDN controller - which then orchestrates, mediates, and facilitates communication between applications wishing to interact with network elements and network elements wishing to convey information to those applications. The controller then exposes and abstracts network functions and operations via modern, application-friendly and bidirectional programmatic interfaces.
  • So, as you can see, software-defined, software-driven, and programmable networks come with a rich and complex set of historical lineage, challenges, and a variety of solutions to those problems. It is the success of the technologies that preceded software-defined, software-driven, and programmable networks that makes advancing technology based on those things possible. The fact of the matter is that most of the world's networks - including the Internet - operate on the basis of IP, BGP, MPLS, and Ethernet. Virtualization technology today is based on the technologies started by VMware years ago and continues to be the basis on which it and other products are based. Network attached storage enjoys a similarly rich history.
  • I2RS has a similar future ahead of it insofar as solving the problems of the network, compute, and storage virtualization as well as those of the programmability, accessibility, location, and relocation of the applications that execute within these hyper virtualized environments.
  • รู้จักกับ OpenFlow:
    virtualnetsystems.com/?p=220
Who Moved my CLI? - Coding to save network admin time:One skill applies to many tasks:
  • Writing code applies to many products in the Cisco family
  • Nexus 3/5/6/7/9K:
    On-box Python
  • Nexus 9K:
    Off-box Python, Bash, NX-API
  • Cisco XNC:
    Java OSGi, REST
  • Future - ACI / APIC / 9K:
    REST, Python, etc
  • And outside...:
    All major OS'

    #!/usr/bin/env python
    print('Hello World!')
  • One very interesting and bright one is the Open Daylight Project. Open Daylight's mission is to facilitate a community-led, industry-supported open source framework, including code and architecture, to accelerate and advance a common, robust software-defined networking platform. To this end, Open Daylight is hosted under the Linux Foundation's umbrella and will facilitate a truly game-changing, and potentially field-levelling effort around SDN controllers. This effort will also spur innovation where we think it matters most in this space: applications. While we have seen many advances in controllers over the past few years, controllers really represent the foundational infrastructure for SDN-enabled applications. In that vein, the industry has struggled to design and develop controllers over the past few years while mostly ignoring applications. We think that SDN is really about operational optimization and efficiency at the end of the day, and the best way to achieve this is through quickly checking off that infrastructure and allowing the industry to focus on innovating in the application and device layers of the SDN architecture.
Network Administration In most environments Today:
  • Manual process using Notepad, copy/paste and patience and pain
  • Some processes are automated using fixed third-party tools
  • Custom expect scripts
Typo in the pasted config? Start from scratchChallenges:
  • Tasks are: manual, repetitive, error-prone
  • This wastes time, talent and typing
  • Manual processes are meant for machines, not men
  • A majority of tasks in IT can be automated, but networking has lagged behind
New Opportunities:
  • Programmability in network equipment will enable you
  • Save time
  • Increase efficiency
  • Decrease quality leakage
  • ทำความรู้จักกับ Mininet - Network Emulator รองรับการใช้งาน OpenFlow
    virtualnetsystems.com/?p=232
Use cases:Script usage guidance:
  • Scripts shown here are running on a Nexus 3064 version 5.0(3)U3(2)
  • These are running on-box
    You will need to scp to scripts to bootflash: to run them
  • Modifications may be needed for your environment
Simple Use Cases:
  • Proactive:
    Get ahead of application issues, monitor services and gather network information in real-time
  • Efficient:
    Create super-commands to encompass multiple troubleshooting steps in one command
  • Scale:
    Execute repetitive commands without typing them all out
1. Application Monitoring:
  • Application teams have their own monitoring
  • The network team doesn't know about problems until they get a P1 case
  • How can we code our way out of this?
  • Write a script that proactively monitors a server attached to an access switch
    If it fails, run some debug commands at that very instant
  • The distributed control plane and its eventual consensus model have evolved over time to try and satisfy not only the continual scale/growth of the Internet in general but to address the concerns of network operators around consistency (black-hole and loop avoidance) and fast convergence.
cool.gif
 

PlAwAnSaI

Administrator
#!/usr/bin/env python
import socket
import time
from cisco import *
from argparse import ArgumentParser

parser = ArgumentParser('Server health monitor')
parser.add_argument('-s', '--server', help='IP address of server to monitor', required=True)
parser.add_argument('-p', '--port', help='TCP port to poll', type=int, required=True)
parser.add_argument('-c', '--commands', help='Commands to run if an interface fails, use ; to separate multiple commands', required=True)
args = parser.parse_args()
connected = False
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if sock.connect_ex((socket.gethostbyname(args.server), int(args.port))) == 0:
connected = True
sock.close()
except socket.error:
connected = False
if connected == False:
with open('servermon.log', 'a') as f:
f.write('The server %s failed on port %s at time %s. Debug output below:' % (args.server, args.port, time.asctime()))
for cmd in args.commands.split(';'):
f.write(cli(cmd)[1])
time.sleep(30)

R1# python servermon.an -s 10.9.46.202 -p 23 -c "show int vlan 20:show proc cpu"

R1# show file bootflash:servermon.log
e2N2VR.jpg
  • In this paradigm, the fundamental concept of an underlay and overlay abstraction gained widespread acceptance (exemplified by IP forwarding and the overlay abstraction of MPLS).
2. Super-commands:
  • NOC engineers log into a switch and run the same commands day-in, day-out
  • These are talented individuals whose time is money
  • How can we code our way out of this?
  • Let's combine multi-command tasks into super-commands
#!/usr/bin/env python
from cisco import *
from argparse import ArgumentParser

parser = ArgumentParser('Supercommand')
parser.add_argument('ip')
args = parser.parse_args()
ip = args.ip

for arp in CLI('show ip arp %s' % (ip), do_print=False).get_output():
if ip in arp: break
else:
raise Exception('Unable to find %s in ARP output' % ip)

ip, timer, mac, interface = arp.split()

for cam in CLI('show mac address-table address %s' % (mac), do_print=False).get_output():
if mac in cam: break
else:
raise Exception('Unable to find %s in CAM output' % mac)

cam_fields = cam.split()
if cam_fields[0] == '*': cam_fields.pop(0)
vlan, mac, entrytype, age, secure, ntfy, port = cam_fields

for cdp in CLI('show cdp neighbor interface %s' % (port), do_print=False).get_output():
if port in cdp: break
else:
raise Exception('Unable to find %s in CDP output' % port)

print('Here is some information on %s:' % ip)
print(' ' * 4 + 'MAC address: %s' % mac)
print(' ' * 4 + 'Local interface: %s' % port)
print(' ' * 4 + 'VLAN: %s' % vlan)
print(' ' * 4 + 'L3 gateway: %s' % interface)
print(' ' * 4 + 'CDP details: %s' % cdp)R1(config)# cli alias name supercommand python supercommand.pyR1# supercommand 10.9.46.202
YYkXaA.jpg
  • The chief weaknesses of the distributed control model are in the areas of network flexibility and user control (there is not enough granular control over the consensus path selection to provide sufficient flexibility), programmability (there is no standard API to inject state or extract information and most automation is either vendor dependent or heavily embedded with knowledge of vendor configuration/operation command semantics), as well as the high degree of integration of its control, data, service, and management planes (driving a scale upgrade cycle and other dependencies). Elements in this model have only recently begun to experiment with the externalizing the control plane so that the route processor can run on more scalable (and easily upgradeable) compute platforms (that are not bound by the drag introduced in creating specific carriers and fabric interfaces for an in-shelf processor).
  • It could be argued that the recursion through an interaction of the IGP/BGP/MPLS paradigm introduces a good deal of complexity and overhead. However, models are also evolving a number of integrated convergence, high-availability, and black-hole avoidance mechanisms that providers find desirable.
  • Centralizing the control plane in a logically centralized but physically distributed model makes sense from scale, high-availability, and geographical perspectives.
  • SDN advocates can learn from historical attempts at centralization. Two examples are provided; ATM LANE (which is truly historical) and the route server (still used in the IP forwarding domain).
3. Ping a Range:
  • Sometimes you need to find a free IP
  • Sometimes you need to check which hosts are up, which are down
  • Sometimes you only have access to the switch
  • How do we code our way out of this?
  • Write a python script that will ping a range of IP addresses
#!/usr/bin/env python
import re
from cisco import *
from argparse import ArgumentParser

def expandrange(rnge):
if '-' in rnge:
r = rnge.split('-')
return range(int(r[0]), int(r[1])+1)
else:
return [rnge]

parser = ArgumentParser('pingrange')
parser.add_argument('ip')
parser.add_argument('-o', '--options', help='Options to pass to ping, default: count 1', default='count 1')
args = parser.parse_args()
target = args.ip

octets = target.split('.')
for o1 in expandrange(octets[0]):
for o2 in expandrange(octets[1]):
for o3 in expandrange(octets[2]):
for o4 in expandrange(octets[3]):
ip = '%d.%d.%d.%d' % (int(o1),int(o2),int(o3),int(o4))
print('%s - ' % ip),
m = re.search('([0-9.]+% packet loss)', cli('ping %s %s' % (ip, args.options))[1])
print m.group(0)R1# python pingrange.py 10.1.1.1-10
yRZBLd.jpg


  • The LANE system of servers provided the first glimpses into the complexities of high availability in a centralized model. Their high-availability model lacked synchronization and often required the user to manually maintain the LECS database in a specific order. These models significantly increased the scale of the control plane infrastructure (in the form of a very large VCC fan out between servers and elements).
  • The more modern route server and route reflector provide a centralized control point for an otherwise distributed IP control plane. These control points are considered the "opportunity point" for SDN development.
Where do I start?
  • Leverage free online resources for learning:
    www.codeacademy.com
    www.coursera.org
  • Practice:
    Find a task you do on a daily basis
    See if you can automate it
    Python runs on all major OS' (including iPhone)
  • Learn from existing scripts:
    github.com/datacenter
cool.gif
 

PlAwAnSaI

Administrator
  • Both of these central control points reduce the scale of the distributed control infrastructure. The route server provides programmability, but not in standardized fashion, and doesn't introduce any more flexibility or granularity of control. The same can be said for the route reflector, though many service providers use automation on top of the route reflector to influence forwarding in their networks. Though the route server has specific applications layered on top of its database (e.g., WHOIS), it doesn't directly provide additional application services to programmers (e.g., topology).
  • OpenFlow (and its accompanying SDO, the ONF) is credited with starting the discussion of SDN and providing the first vestige of modern SDN control: a centralized point of control, a northbound API that exposes topology, path computation, and provisioning services to an application above the controller), as well as a standardized southbound protocol for instantiating forwarding state on a multivendor infrastructure.
  • Unfortunately, the OpenFlow architecture does not provide a standardized northbound API (yet), nor does it provide a standardized east-west state distribution protocol that allows both application portability and controller vendor interoperability. Standardization may progress through the newly spawned Architecture Working Group.
Security for the SDN, by the SDN - Address Security Systematically:Overview of SDN:
  • 1) Programmable APIs:
    Control Plane & Data Plane
  • 2a) Classic SDN:
    Controller Data Plane
  • 2b) Hybrid SDN:
    Controller Control Plane & Data Plane
  • 3) Overlay Virtualization:
    Virtual Control Plane & Data Plane Overlay Protocols (e.g. VXLAN) Control Plane & Data Plane
Cisco Open Network Environment (ONE):
  • Applications
  • Virtual Overlays
  • Controllers and Agents
  • Platform APIs
Industry's Most Comprehensive Networking Portfolio:
  • Hardware + Software
  • Physical + Virtual
  • Network + Compute
Security Landscape:Biggest Security Challenges:
  • Maintain Security and Compliance with business models change (Agility)
  • Stay ahead of the threat landscape
  • Reduce complexity of security solutions
The Threat Landscape is evolving:
  • 2000 - Worms > Antivirus (Host-Based)
  • 2005 - Spyware and Rootkits > IDS/IPS (Network Perimeter)
  • 2010 - APTs Cyberware > Reputation (Global) and Sandboxing
  • Tomorrow - Increased Attack Surface > Intelligence and Analytics (Cloud / SDN)
Anatomy of a Modern Threat:
  1. Infection entry point occurs outside
  2. Advanced cyber threat bypasses perimeter defence
  3. Threat spreads and attempts to exfiltrate valuable data
Network planes:
  • Data Plane:
    The Data Plane of the network is made up of user and application data transiting your network infrastructure
    All Packets Forwarded Through the Platform
  • Control Plane:
    The Control Plane of a network consists of the protocols that enable the network elements to function cooperatively
    ARP, BGP, OSPF, NTP ... and Other "Glue" Protocols
  • Management Plane:
    The Management Plane of the network is made up of the protocols that support the operational needs of the network:
    • Without the Management and Control Planes, the Data Plane will cease to function
    • The resiliency of the Control Plane is vital to the success of the Management and Data Planes, it is critical that control plane resources and protocols are protected
    • Without the Management Plane, it might be impossible to return the network to a functional and secure state
    SSH, TFTP, SNMP, FTP ... and Other Mgmt Protocols
  • CEF Forwarding Path - Receive/Host Path, Transit/Exception Path, Multiple Paths for Punted Packets -> Route Processor CPU
Typical DoS:
  1. Attacker target multiple network devices
  2. Generate invalid flow request on each device
  3. Causes DoS on each device
SDN DoS:
  1. Attacker target one of the network devices
  2. Injects false network flow requests using data plane
  3. Controller process flow requests > Controller CPU utilization goes high
  4. Invalid network flows pushed by control plane to network devices
  5. Invalid flows installed on all data planes and network-wide DoS
Network Programmability:proactive versus Reactive Applications:proactive:
  • Human > Server > Application > Device
  • Intermittent changes
  • Automated configuration at scale
Proactive is a type of application sets configuration parameters for planned network changes.

Reactive:
  • Events/Device > Server > Application > Device
  • Frequent and dynamic changes
  • Responding to network events
CLI versus NETCONF Applications:CLI Applications:
  • Human > Device
  • Support all devices
  • Made for humans
NETCONF Applications:
  • Server > NETCONF Application > Device
  • Support many devices
  • Made for applications
CLI is a type of interface is available for almost every networking device. While NETCONF and RESTCONF are becoming more common, they are not yet available on many networking devices. XML is a structured data format, not an interface type.

YANG is a data model is used by the NETCONF protocol.

Standalone versus Controller-based Applications:Standalone Applications:
  • Server > Application > Device
  • Application performs discovery, topology, device communication
Controller-based Applications:
  • Application > Server > Controller > Device
  • Controller performs discovery, topology, device communication, abstraction
External and internal are two varieties of controller-based applications.

Standalone is a type of application communicates directly with a device.

External Support Libraries:python code from other sources
  • Python
  • Cisco (DevNet, Learning Labs)
  • External Sources:
    • Device communication
    • Data formats
    • Printing
Types of Network Programmability:

In general, network programmability is broken down into two high-level categories: device-level programmability and true network-level programmability. Device programmability in and of itself is prone to some of the same scalability challenges as CLI but provides a more reliable and machine-consumable interface to the devices. True network-level programmability treats the network as an object that allows for more advanced solutions that tend to veer toward business use cases. Network-level programmability is enabled by controllers such as the APIC. The APIC controller allows data centre engineers to define policies that describe how the network should function. The controller instantiates these policies in the data centre switches without the need to configure each switch separately.

CLI versus NETCONF:

CLI scripting was the primary approach to making automated configuration changes to the network prior to NETCONF. CLI scripting has several limitations including lack of transaction management, no structured error management, and ever-changing structure and syntax of commands that make scripts fragile and costly to maintain.
cool.gif
 

PlAwAnSaI

Administrator
Standalone versus Controller-based:

Network programmability applications can be proactive or reactive, they can use CLI or NETCONF; they also can be standalone or controller-based.

Standalone applications have the following characteristics and considerations:

  • Communication to each device is direct, from your application directly to the device. Compare with controller-based, where communication goes through a translation process as it goes through the controller, before being sent to the device.
Leveraging Existing Code:

Paramiko is a library provides a Python implementation of SSH. Pexpect can also be used to support SSH.

Creating Your First Python Program:

Program Basics:
  • 'Hello Device'
A simple introductory application that uses the pexpect library and pings a network device.
  • Demo!
  • Numbers, Strings, and Variables
A quick introduction to Python numbers, strings, and variables.
  • Code Blocks
An overview of how code blocks are defined in Python.
  • Printing
A brief look at printing variables using Python commands
  • Comments
The importance of commenting code, and the mechanisms for doing so.30. hello-device.py
  • Tell Python to use the 'pexpect' library:
    import pexpect
    The import statement tells Python to import all of the functions contained in the external library named pexpect.
  • Set the ping options:
    ping = pexpect.spawn('ping -c 5 localhost')
    pexpect.spawn is using the pexpect library to create, or spawn, a command process. The information inside the parenthesis is telling the spawned process to ping the localhost five times.

  • result = ping.expect([pexpect.EOF, pexpect.TIMEOUT])
    print(ping.before)

    * pexpect.spawn and pexpect.run() are not available on Windows, as they rely on Unix pseudoterminals (ptys). Cross-platform code must not use these.
ghASoT.jpg


Numbers:

  • 0b10100 -> Binary base
  • 0o12 -> Octal
  • 98 -> Decimal
  • 0x78A4 -> Hexadecimal
Integers:
  • Whole numbers (eg 5)
  • Can be very large
  • Can be negative
  • Can be other bases (eg binary, hexadecimal)
Floats:
  • Floating point (eg 5.2)
  • Exponential notation
  • Can be negative
  • Represent real numbers
Arithmetic operations: +, -, *, /, // (truncation), % (modulus), ** (exponentiation), +=, -=, *=, etc.Strings:
  • Quotes: Strings are created/delimit with Single quotes (') or Double quotes (")
  • Modification: Strings can be concatenated using '+'
  • Slicing: Strings can be sliced using '[start:end:step]'
  • Splitting: Split strings using 'split()'
  • Length: Get length using 'len()
  • Single character: Get character using '[index]'
    print "Aardvark"[2]
    Output: r
    The [2] means to print the character at index 2 - Python counts from 0, so index 2 is the third character in the string.
  • Special characters: Special characters escaped using '', e.g. 'n' for newline.
Other operations: join, replace, duplicate, convert, and others.Variables, Objects, References:
  • Objects: Everything in Python is an object.
    x = 2
    y = x
    x = 4
    print y
    Output: 2
    When the 'y = x' is executed, the value of y is set to 2. Changing the value of x has no impact on the value of object y.
  • Variables: Variable names are just references to an object.
    username = 'cisco'
  • Assignment: Assignment means assigning a variable name to an object.
    new_username = username
  • Modification: Reassignment of a variable name means it references a completely new object
    username = username + '123'
Code Blocks: Indentation:
  • No 'begin' 'end', no '{' '}' to enclose code blocks.
  • Blocks are identified by ':' and indentation:
    if a == b:
    # do something here
    # do more things
    else:
    # do else type things
  • All code in code block must be indented identical numbers of spaces (no tabs please)
  • Code block ends when indentation ends.
Commenting Your Code:Importance of Comments:pro: "Half non-whitespace should comment"Con: "Source code should be self-documenting"Comments should:
  • Explain why (the what is generally obvious)
  • Be maintained and maintainable
  • Be suitable for automatic document generation
Single-line comments:
  • '#' denotes comment
  • Quick explanation of non-intuitive code
  • Explanation of this step in process
  • Don't state the obvious
Multi-line comments:
  • Triple quotes
    x = 1
    x = 2
    " " "
    x = 3
    x = 4
    " " "
    print x
    Output: 2
    First " " " begins a comment block, which is closed by the second " " ". x = 3 and x = 4 are not executed.
  • At beginning of module
  • At beginning of function
    • Purpose of function
    • Parameters
    • Return values
  • Collected by document generation tool (pydoc)
PyDoc Auto / Automatically Program Documentation / Auto-Doc Generation / Generating:In your code:
  • Document module
  • Document functions (purpose, parameters, return value)
Generate documentation:
  • Run 'pydoc'
  • Point it at source code
  • Output is well-organized and structured documentation of your module
    Pydoc generates documentation from multiline comments in modules and functions in well-commented code.
Designing and Implementing Cisco Network Programmability:
  • Minimizing the number of manual interactions with the network
  • Reduce operational inefficiencies
  • Improve productivity
  • Create Scripts
  • Create Code
  • Work with sending and receiving information using commands sent via a web browser
  • Linux
  • Python - Relatively simple language
  • What is an SDN? - Software Defined Network
  • APIs
    • Enable a much more robust means of managing network devices than traditional methods
    • Native REST
    • NETCONF
    • RESTCONF
  • XML
  • JSON
  • YANG
  • SDN Controllers alleviate the problems by centralizing management of many devices in one single point of administration
  • OpenFlow
  • OPEN DAYLIGHT
  • APIC-EM
  • Efficiency
  • Reliability
  • Collaboration
Understanding Software-Defined Networking:What is Software-Defined Networking?:
  • An approach and architecture in networking where control and data planes are decoupled and intelligence and state are logically centralized.
  • Enablement where underlying network infrastructure is abstracted from the applications [network virtualization].
  • A concept that leverages programmatic interfaces to enable external systems to influence network provisioning, control, and operations.
  • Is SDN one or more of these statements?
Software-Defined Networking is:
  • An approach to network transformation
  • Empowering external influencers to network design and operations
  • Impacting the networking industry - challenging the way you think about engineering, implementing and managing networks
  • Providing new methods to interact with equipment/services via controllers, APIs
  • Normalizing the interface with equipment/services
  • Enabling high-scale, rapid network and service provisioning/management
  • Providing a catalyst for traditional Route/Switch engineers to branch-out
cool.gif
 

PlAwAnSaI

Administrator
Software-Defined Networking is NOT:
  • An easy button... [but is intended to make things easier for all!]
  • A panacea or end-state
  • Narrowly defined
  • Designed to replace network engineers
  • A mandate for all network engineers to become programmers
  • A new attempt at network evolution
Traditional versus Software-Defined Networks:The Traditional Network:
  • Control plane learns/computes forwarding decisions.
  • Data plane acts on the forwarding decisions.
  • Control and Data Plane resides within Physical Device
The Network As It Could Be... to an SDN 'Purist':
  • Control plane becomes centralized
  • Physical device retains data plane functions only
The Network As It Could Be... In a 'Hybrid SDN':
  • A Controller is centralized and separated from the Physical Device, but devices still retain localized Control plane intelligence.
Why Change?:
  • Familiar Manual, CLI-driven, device-by-device approach is inefficient
  • Increased need for programmatic interfaces which allow faster and automated execution of processes and workflows with reduced errors
  • Need for a 'central source of truth' and touch-point
Current Industry Trends:Networking Trends:
  • Open Source Software
  • Programmable Infrastructure
  • Software Defined Networking (SDN) is set of techniques, not necessarily a technology, used to control, manage, and change the way networks are built and managed.
  • DevOps
  • Application Centric Networking
Open Source Software:
  • OpenFlow:
    • Emerged out of Stanford
    • Low-level imperative control for FIB tables
    • Used between controllers and switches
  • Contiv:
    • Several projects
    • Working to define operational policy for container-based applications
  • .IO:
    • Acceleration of NFV data planes
    • Vector packet processing (VPP)
  • OvS - Open vSwitch:
    • Open source feature rich virtual switch
    • Supports OpenFlow and OVSDB
  • OpenStack - CLOUD SOFTWARE:
    • Open source Cloud Computing Project
    • Collection of APIs
    • Neutron is the network project and API standard to have a network plug-in
  • OPEN DAYLIGHT:
    • Collaborative project
    • Promote community-driven SDN
  • Goals:
    • Community involvement in continuous improvement
    • Using open APIs to interact with network devices
Programmable Infrastructure:platform specific, on-box, automation and scripting mechanisms:
  • TCL
  • EEM
  • Power on Auto Provisioning
  • Smart Install
  • Smartports Macros
  • Python
Characteristics of modern programmatic protocols for managing network devices:
  • REST APIs
  • NETCONF
  • RESTCONF
  • SDKs
  • DevOps Tools
  • Linux
Software Defined Networking:
  • Control Plane and Data Plane Separation
  • Software Only Network Virtualization
  • Network Function Virtualization
  • Disaggregation
  • Device APIs
  • Policy and Application Centric Infrastructure
DevOps - Best described by understanding CALMS:
  • Culture
  • Automation
  • Lean
  • Measurement
  • Sharing

    ->
  • Increase Deployment Frequency
  • Decease Failure Rate
  • Faster Time to Market
  • Increase Speed and Accuracy of Bug Fixes
  • Operating Systems:
    • Linux
    • debian
    • redhat
    • ubuntu
  • Programming Languages:
    • Go
    • RUBY
    • python
  • Configuration Management:
    • SALTSTACK
    • ANSIBLE
    • Chef
    • puppet
  • Continuous Integration:
    • circleci
    • Buildbot
    • Travis CI
    • Jenkins
  • Version Control:
    • git
    • GitHub
    • Bitbucket
Cisco ACI - Application Centric Infrastructure:
  • Simplifies, optimizes, and accelerates the application deployment lifecycle.
  • Employs an open-ecosystem approach integrating physical and virtual elements.
  • Supports open APIs, open standards, and open source elements to enable greater flexibility for development and operations.
  • APIC
  • Agility and Visibility
  • Simplicity
  • Automation
  • Scale and Performance
  • Security
  • Open
Network Programmability & Automation:Current Network Operation:
  • CLI was built for manual human interaction
  • Configuration is one device at a time
  • Copying and pasting are the standards
  • Configuration is prone to error
  • Tasks are not easily repeatable
  • Notepad is the most common text editor
Future Network Operation:
  • Version controls all configurations monitoring changes
  • Version control is the source of the truth
  • Automated systems perform testing before any change is made to the configuration including system, style, reachability, etc.
Uses of Network Automation:Types of Network Automation/programmability techniques can perform:
  • Common tasks:
    • Device Provisioning
    • Data Collection & Telemetry
    • Compliance Checks
  • Reporting
  • Troubleshooting
Network Automation Scenarios:Data Collection:
  • For a Cisco ISE deployment, an IT manager needs to perform an audit of network switches to gather the hostname, IP address, platform, and serial numbers from all network devices in the organization.

    42cde6540b549c1e5.jpg
  • Correlate user switchport given their IP Phone Extension
Configuration Management Scenarios:
  • Due to new vulnerability, new ACLs needed to be added to Cisco ASA FWs at each branch site.
  • ISE Deployment requires commands on each and every switch.
  • Enterprise needs to add BGP peers frequently for business partners.
  • Documented processes lend themselves to automation.
Management Plane:NMS / End-User Network Device: Management Plane, Control Plane, and Data PlaneWhy Is Network Automation Different Now?:
  • PERL, Expect, and SSH connectivity has existed for years
  • It was possible - tedious and error prone, but possible
  • Manual parsing - lots of regular expressions
  • Going forward:
    • Programmatic APIs
    • No parsing
    • Automatic failure on rollback
    • Configuration changes as a transaction
Open Source Tools and Enterprise Platforms:Enterprise Systems Operations:
  • VMware vCenter
  • Microsoft System Center
  • vRealize
  • BMC
  • HP
Enterprise Network Operations:
  • Cisco Application Centric Infrastructure (ACI)
  • Cisco Open SDN Controller (OSC)
  • Cisco WAN Automation Engine (WAE)
  • Cisco Network Services Orchestrator (NSO)
  • Cisco Application Policy Infrastructure Controller Enterprise Module (APIC-EM)
Open Source Software:
  • Linux
  • ANSIBLE is an example of an off-box method network operations teams use for managing network devices.
  • puppet
  • SALTSTACK
  • Chef
  • RUBY
  • python
cool.gif
 

PlAwAnSaI

Administrator
Network Programmability Technology:
  • Linux
  • Device and Controller APIs
  • Version Control
  • Software Development
  • Automated Testing
  • Continuous Integration
  • GitHub
  • git
  • NX-API Developer Sandbox
  • python
  • Travis CI
Network Automation Workflow:Configuration Management Workflow [Sample]:
  • configs/fix_routing_policy
    - Review Config Changes ->
  • Automated Testing
    Travis CI - merge ->
    tests:
    • Functional
    • Performance
    • Syntax
  • Upstream (remote)
    Code/Config/Project
    configs/master
    git, GitHub - git clone ->
  • Your Local Environment
    configs/master
    git branch fix_routing_policy
    configs/fix_routing_policy
Cisco Platforms and APIs:
  • Platform(s) | Programmatic API(s)
  • IOS XE | NETCONF, RESTCONF
  • IOS XR | NETCONF, RESTCONF, gRPC
  • Nexus | NX-API CLI, NX-API REST, NETCONF
  • Adaptive Security Appliances (ASA) | REST
  • Application Centric Infrastructure (ACI) | REST
  • APIC-EM | REST
  • Cisco platforms use NETCONF/RESTCONF and NX-API to provide network operators off-box programmability.
Linux Primer for Network Engineers:Why Learn Linux?Linux is everywhere - Used in various devices:
  • Mobile devices
  • Desktop Computers
  • Production Servers
  • Hypervisors
  • Network switches
cisco@cisco: $ sudo su -
[sudo] password for cisco:
root@cisco: # exit
logout
cisco@cisco: $
  • redhat
  • debian
  • CentOS
  • fedora
  • ubuntu
Though Linux is pervasive in technology, a network programmability engineer should learn Linux because:
  • Network devices now expose the underlying Linux shell
  • Network devices now enable engineers to run containers on the actual network device
  • Most software development environments are Linux-based
  • New open source projects such as Open vSwitch, Docker, and OpenStack all have a Linux foundation
Navigating the Linux File System:Super User Privileges:
  • The sudo command is short for "super user do"
  • necessary to Run a program as other users (ex: root privileges by default)
  • Can configure who can run sudo commands in the "sudoers" file
  • Debian/Ubuntu distros do not enable the root user
Basic Commands:
  • pwd | Print working directory
  • ls | List contents of the working directory
  • man | View man pages (how-to) to learn how to use a given command and it's flags
Paths and Directories:
  • Relative Path
    • Address relative to the current, or working, directory
  • Absolute Path
    • Address relative to the root directory
cisco@cisco: /scripts$ pwd
/home/cisco/scripts
cisco@cisco: /scripts$ cd cisco
cisco@cisco: /scripts/cisco$ cd /var/log
cisco@cisco: /var/log$ pwd
/var/log
  • Linux uses a single root file system which means all directories exist inside a single namespace referred to as /.
Change Directories:
  • cd .. | Change current directory to parent directory
  • cd | Back to the home directory
  • cd ../.. | Back two directories (there is no limit on this)
  • cd - | Moves back to the previous working directory
Linux Distributions:Debian:
  • Free open source OS developed under the Debian Project
  • Latest stable release is codenamed "stretch"
  • Derivatives include Ubuntu and Mint (derivative of Ubuntu)
Red Hat Enterprise Linux:
  • Red Hat's official commercial, distribution of Linux for training, services, and support
  • RHL discontinued for RHEL
  • Derivatives include Fedora and CentOS
  • Kali Linux focused on penetration and security testing
  • OpenWrt focused on home router functionality
Package Management:
  • Packages are a convenient method to deliver software
  • Package tool maintains a database of installed applications
  • Two main CLI tools required to install, update and remove software
Red Hat Family:
  • rpm | Install local rpm package
  • yum | Download and install a package from repositories
  • .rpm | File extension
  • cisco@cisco: $ sudo yum install traceroute
  • cisco@cisco: $ sudo rpm -i .rpm
Debian Family:
  • dpkg | Command to install a local .deb package
  • apt & apt-get | Commands to download and install packages
  • .deb | File extension
  • cisco@cisco: $ sudo apt-get install traceroute
  • cisco@cisco: $ sudo apt install traceroute
  • cisco@cisco: $ sudo dpkg -i .deb
Working with Files and Directories:touch
  • Updated timestamps of files and creates an "empty" file
cisco@cisco: $ touch catalyst_config.txt
cisco@cisco: $ ls
catalyst_config.txt cisco Desktop Documents Downloads Templates
cisco@cisco: $ ls -l catalyst_config.txt
-rw-rw-r-- 1 cisco cisco 0 Jun 24 11:50 catalyst_config.txtMake Directory Commands:
  • mkdir | Make a new directory
  • mkdir -p | Make all required sub-directories in the path
Remove Commands:
  • rm | Removes a file
  • rm -r | Removes an entire directory and its contents
  • rmdir | Removes an entire empty directory
  • rm -rf | Removes a directory and contents including write-protected files
Copy and Move Commands:
  • cp | Copy a file
  • mv | Move/rename a file
cisco@cisco: /Nexus9000$ cp file1 file2
cisco@cisco: /Nexus9000$ mv file2 file3
cisco@cisco: /Nexus9000$ ls
file1 file3cisco@cisco: $ mv class.txt MyClass is moving a file that is called class.txt from its current directory to a directory called MyClass.
Viewing Files Commands:
  • more | similar to using Cisco CL - space bar takes you down a full-screen length (% in the bottom left).
  • less | "less is more" because it allows the user to scroll up and down using arrow keys vs. just the ability to space down.
  • cat | Streams the file top to bottom without pausing.
  • head | By default shows first 10 lines of a file.
  • tail | By default shows last 10 lines of a file.
  • diff | View diff between two files (hint: use -c option).
File Permissions:Linux operating systems are multi-userPermissions are based on two factors:
  • Permissions assigned to a specific user and group
  • Permissions assigned to a specific action (read, write, execute)
drwxrwxrwx:
  • d - File Type
  • First rwx - User
  • Second rwx - Group
  • Last rwx - Other
cisco@cisco: $ ls -l vlans_script.py
-rw-rw-r-- 1 cisco cisco 0 Sep 12 15:14 vlans_script.py
cisco@cisco: $ chmod u+x vlans_script.py
cisco@cisco: $ ls -l vlans_script.py
-rwxrw-r-- 1 cisco cisco 0 Sep 12 15:14 vlans_script.py
cisco@cisco: $ chmod go+x+w vlans_script.py
cisco@cisco: $ ls -l vlans_script.py
-rwxrwxrwx 1 cisco cisco 0 Sep 12 15:14 vlans_script.py
cool.gif
 

PlAwAnSaI

Administrator
Linux Processes:Viewing Running Processes:
  • top
    • Displays real-time processor utilization
  • htop
    • Displays real-time processor utilization in an easier to read format
  • ps
    • Display active processes
  • ps aux
    • Displays an exhaustive list of all processes by all users
42bea18486e6f0f59.jpg

  • kill
    • Ends a running process
    • Used along with the process ID (PID) to kill an individual process
    cisco@cisco: $ kill 2442
  • grep
    Search the contents of a file for a specified value
Using the Linux Command Line:package Management:
  • sudo apt-get install tree
    Install the Linux package called tree
  • tree
    View the directory structure from current working directory
  • traceroute cisco.com
    Perform a traceroute to cisco.com
Navigating the Filesystem:
  • pwd
    Print current working directory
  • ls
    View the list of files in current directory
  • cd /etc
    Navigate to the /etc directory
  • cd
    Back to the home directory
  • cd /courses/npdesi
    Navigate to the courses/npdesi sub-directory
  • cd ../..
    Go back two directories
  • cd -
    Moves back to the previous working directory
Working with Files and Directories:
  • mkdir -p scripts/test/switches
    Create the following tree structure: scripts/test/switches
  • mkdir catalyst
    Create subdirectory that is called catalyst
  • touch catalyst_3850.txt
    Create a new file catalyst_3850.txt
  • mv nexus_5548.txt ../nexus
    Move the file nexus_5548.txt from the current working directory to the nexus directory
  • mv catalyst_3850.txt catalyst.txt
    Re-name the file catalyst_3850.txt to catalyst.txt
  • cat hq-router.txt
    Stream a file called hq-router.txt entire contents to the terminal
  • less asa.txt
    Display a file called asa.txt contents one screen length at a time on the terminal and can scroll up and down within the output of a file
  • diff interface_1.txt interface_2.txt
    Compare (perform a diff) interface_1.txt and interface_2.txt
  • chmod
    Change a file's permission
Python Foundation for Network Engineers:Why Learn Python?:
  • Interpreted Scripting Language
  • Low barrier to entry compared to other languages
  • Can be used to write various types of Python Applications
  • Python Execution Engine exists on most Linux distributions including network operating systems, such as NX-OS
Python 2.x:
  • No longer under active development, but supported by the Python community
  • Better library support
  • Default on Linux and Mac
  • Supported by Cisco NX-OS
Python 3.x:
  • Under active development
  • Designed to be easier to learn
  • Fixed major issues are 2.x
  • Not backward compatible
Using the Dynamic Interpreter (shell):
  • cisco@cisco: $ python
    >>>
    To exit the shell, use exit() or CTRL+D
Writing Python Scripts:
  • #!/usr/bin/env python

    if _name_ == "_main_":
    course = 'Designing and Implementing Cisco Network Programmability'
    print course

    cisco@cisco: $ python cisco.py
    Designing and Implementing Cisco Network Programmability
Understanding Python:python Helper Utilities and built-in Function:
  • help() - Returns the python built-in documentation about the object
  • dir() - Returns all available attributes and built-in methods of a given object or module
  • type() - Returns the type of the object
>>> type('1.1.1.1')

>>> dir(str)

## output truncated for brevity ##
>>> help(str.upper)Writing Idiomatic Python:
  • Single-Line comments
  • Multi-line comments
  • Whitespace
  • Indentation
    • Spaces vs. Tabs
  • Python Style Guide (PEP8)
    www.python.org/dev/peps/pep-0008
Common Python Data Types:
  • String
  • Numbers
  • Lists
  • Dictionaries
  • Booleans
  • Files
Variable Assignment:
  • Assign a value to a variable using the equals sign ("=")
  • >>> ipaddr = '10.1.10.1'
    ipaddr was assigned the value of "10.1.10.1"

  • The Python shell is used to write and test code in real time without having to write a full program or script.
  • Python is considered a dynamic language.
Data Types: Strings:
  • Sequence of characters that are surrounded by quotes
  • Immutable - individual characters cannot be natively modified
  • Empty string
>>> ipaddr = '10.1.10.1'
>>> hostname = 'nxos1'
>>> hostname = "nxos2"
>>> hostname[4] = '3'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment
>>> os_version = ''Printing Strings:
  • Using the print statement to print strings
    • Prints the rendered string
  • Typing in the variable name on the Interpreter
    • Print the value as a string literal
>>> interface_config = 'interface Eth1/1n no switchport'
>>> interface_config
'interface Eth1/1n no switchport'
>>> print interface_config
interface Eth1/1
no switchportConcatenate or add one or more strings together:>>> ipaddr = '10.1.10.1'
>>> mask = '255.255.255.0'
>>> ipmask = ipaddr + ' ' + mask
>>> ipmask
'10.1.10.1 255.255.255.0'String Built in Methods:
  • Working with common built-in methods
  • Use dir() on any object to see its available built-in methods
    • .upper()/.lower()
    • .replace() - Replaces characters in a string with a given set of characters
    • .startswith()
    • .format()
    • .split()
>>> hostname = 'nxos1'
>>> hostname.upper()
'NXOS1'
>>> macaddr = '00:11:22:33:44:55'
>>> macaddr.replace(':', '.')
'00.11.22.33.44.55'
>>> ipaddr.startswith('10')
True
>>> ipaddr = '10.{}.1.1'
>>> ipaddr.format('200')
'10.200.1.1'
>>> ipaddr = '10.4.8.1'
>>> ipaddr.split('.')
Data Types: Numbers:
  • Can perform mathematical operations directly in code
  • Integers and Floating Point numbers
  • Operators such as +, -, *, /, //, % are used
>>> 5 * 4
20
>>> 10 - 4
6
>>> 239234 + 4
239238
>>> 10 / 3
3
>>> 10.0 / 3
3.3333333333333335
>>> 10.0 // 3
3.0
cool.gif
 

PlAwAnSaI

Administrator
Data Types: Booleans:
  • Values are True or False
  • Operators are and, or, and not
  • not takes the inverse
>>> True and False
False
>>> True and True
True
>>> False and False
False
>>>
>>> True or False
True
>>> True or True
True
>>> False or False
False
>>>
>>> not True
False
>>> not False
True
>>>
>>> not (True or False)
False
>>>
>>> True or False or False or True
True

Conditionals:
  • Expressions evaluate to True or False
  • Comparison Operators:
    • ==, !=, >, =, >> 9372 > 9396
      False
      >>> 'nexus' != 'catalyst'
      True
      >>> 'nexus' in 'nexus 9396'
      True
      >>> '9372' not in 'nexus 9396'
      TrueConditional Statements:
      • if, elif, else
        elif conditional statements is an optional condition that can be used numerous times to check for multiple expressions of True.
      • End with a colon
      • Consistent indentation required
      >>> switch = 'catalyst 3850'
      >>> if 'catalyst' in switch:
      ... switch_type = 'catalyst'
      ... elif 'nexus' in switch:
      ... switch_type = 'nexus'
      ... else:
      ... switch_type = 'unknown'
      ...
      >>> print switch_type
      catalystSummary:Create Strings:
      • >>> ipaddr = '10.1.1.1'
        >>> print ipaddr
        10.1.1.1
      • >>> mask = '255.255.255.0'
        >>> print mask
        255.255.255.0
      • >>> hostname = 'router_1'
        >>> print hostname
        router_1
      • >>> os_version = '15.4'
        >>> print os_version
        15.4
      • >>> switch = 'NEXUS'
        >>> print switch
        NEXUS
      • >>> ipmask = ipaddr + ' ' + mask
        >>> print ipmask
        10.1.1.1 255.255.255.0
      Navigate the Built-In Help Features:
      • >>> campus_switch = 'catalyst'
        >>> print campus_switch
        catalyst
      • >>> type(campus_switch)

      • >>> dir(campus_switch)
        ...

      • >>> help(campus_switch.upper)
        Help on built-in function upper:

        upper(...)
        S.upper() -> string

        Return a copy of the string S converted to uppercase.

        >>> help(campus_switch.startswith)
        Help on built-in function startswith:

        startswith(...)
        S.startswith(prefix[, start[, end]]) -> bool

        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        the prefix can also be a tuple of strings to try.
      Use Built-in Methods of Strings:
      • >>> 'nxos1'.upper()
        'NXOS1'
      • >>> description = "The device type is an {}"
        >>> description.format('ASR')
        'The device type is an ASR'
      • >>> ip = '10.1.1.1'
        >>> ip.startswith('100')
        False
      • >>> ip.split('.')[0]
        '10'
        >>> ip.split('.')[3]
        '1'
      • The associated return data type:
        • upper() and string
        • startswith() and boolean
        • split() and list
      • >>> 'Eth1'.lower().startswith('et')
        True
        >>> 'Eth1'.startswith('et')
        False
      Use Conditionals:
      • >>> router = 'asr_1006'
        >>> print router
        asr_1006
      • >>> if router.startswith('asr'):
        ... router_type = 'asr'
        ... elif router.startswith('isr'):
        ... router_type = 'isr'
        ... else:
        ... router_type = 'unknown'
        ...
        >>> print router_type
        asr
      • >>> router = 'nexus9k'
        >>> if router.startswith('asr'):
        ... router_type = 'asr'
        ... elif router.startswith('isr'):
        ... router_type = 'isr'
        ... else:
        ... router_type = 'unknown'
        ...
        >>> print router_type
        unknown
      Programming the Digital Network Architecture (DNA):programming Foundation:Coding 101 - REST API Basics with APIC-EM:What is a Web Service?
      • A web service is a way for two systems to communicate through a defined interface.
      • There are two major types of web services - REST and SOAP.
      What is a REST Web Service?
      • REST is an architecture style for designing networked applications.
      • A REST web service is as easy to call as making an HTTP request.
      • RESTful interfaces usually offer the CRUD (Create, Update, Delete) operations.
      • To know more about REST in general, this is a great REST tutorial: rest.elkstein.org
      What are the benefits of REST?REST Is easy to use on any platform
      RESTisGreat.jpg

      APIC-EM API is a REST API:
      • The Application Policy Infrastructure Control (APIC) Enterprise Module (EM), Application Programming Interface (API), APIC-EM APIs, enables deploying and running application policies across networking infrastructure.
      • Using the APIC-EM APIs, can retrieve information about devices on network including a list of hosts, network devices, or users.
      • Look at the APIC-EM Reference Docs: devnetapic.cisco.com to see the details of the APIC-EM functions.
      How does this work?
      howitworks.jpg
      • REST is centered around the HTTP request and response model. Consuming an API is as simple as making an HTTP request.
      • In this example, request the list of hosts, and that information is returned in the response. The data returned in the response is usually formatted as JSON or XML.
        (JSON -- JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange.)
      What do I need to know to make a Request?To construct a request, determine the following information for the API that are calling. Can find this information in the API reference documentation.
      • Method:
        Choose one of the following http methods:
        • GET - Retrieve data
        • POST - Create something new
        • PUT - Update data
        • DELETE - Delete data
      • URL:
        • Determine the URL of the endpoint want to call.
        • Example: http://{APIC-EMController}/api/v1/ticket
          • Where {APIC-EMController} is the controller IP or hostname.
        • Enter the URL/IP address of an APIC-EM controller on network.
      • URL Parameters:
        • If the endpoint requires URL parameters, pass them as part of the URL. To get this information, refer to the reference documentation for the particular endpoint.
      cool.gif
 

PlAwAnSaI

Administrator
  • Authentication:
    • Determine which authentication type to use. Basic HTTP, token-based, and OAuth are common types.
    • Add the authentication credentials to the API call are preparing.
  • Custom Headers:
    • If required, add any HTTP Headers to the API call are preparing. For example: Content-Type: application/json.
  • Request Body:
    • If required, include a JSON- or XML-formatted request body that contains any data that is needed.
About Authentication:Authentication controls whether a user can access a specific API endpoint and how they can it. For example, one user might have read-only privileges, which they can only make API calls that read data. Another user might have read and change (add, edit, delete) privileges to every endpoint, which means they can make an API call. These access rights are typically-based upon assigned user roles such as Administrator, which grants a user full rights to change data, and User, which grants read-only access.REST APIs have three common methods to authenticate users:
  • Basic HTTP: The username and password are passed to the server as an encoded string.
  • OAuth: Open standard for HTTP authentication and session management. Creates an access token associated with a specific user that also specifies the user rights. The token identifies the user and rights when making API calls to verify access and control.
  1. Token: As with OAuth, a token is created and password with each API call, but there is no session management and tracking of clients. This simplifies interaction between the server and client. APIC-EM uses this design for authentication management.
APIC-EM uses token-based authentication. So the first request need to make creates a token. In APIC-EM, this token is called a service ticket. The controller uses the service ticket to determine which endpoints can access. The service ticket must be included in every API call except the one that creates the ticket.The steps for using the APIC-EM authentication token are:
  1. Create a ticket
  2. A ticket (token) is returned in the response body.
  3. Include this token in the 'X-Auth-Token' header on all subsequent requests.
How to be a Network Engineer in a Programmable Age:Meet Carl the Network Engineer:Networking Skills:
  1. Spanning-Tree
  2. Routing Protocols
  3. QoS
  4. VPN Design
  5. VoIP
  6. Fibre Channel
  7. Security Policy
  8. MPLS
Programming Skills:
  1. TCL
  2. EEM
  3. Expect Scripts
The Network...:
  1. Router
  2. Switch
  3. Server
  4. vSwitch
  5. VM
  6. Blade Switch
  7. lbr
  8. Cloud
  9. Container
  10. Load Balancer
  11. Firewall
  12. IPS
  13. DNS
  14. Gateways
  15. Others...
The OSI Model of Networking...:
  • L7: Application
  • L6: Presentation
  • L5: Session
  • L4: Transport
  • L3: Network
  • L2: Data Link
  • L1: Physical
  • L2 - L4: Oh Yeah... We Got this
  • L1 - L2: Black Magic
  • L5 - L7: Please don't ask about this...
The Four Ages of Networking...:
  1. Stone Age: Spanning Tree, VLANs
  2. Bronze Age: Routing Protocols, WAN Design, IP-magedon
  3. The Renaissance: SDN, OpenFlow, Controllers, Overlays, MP-BGP, VXLAN, Micro-Segmentation, White Box
  4. Programmable Age: Cloud, Python, REST / APIs, NETCONF / YANG, "Fabrics", Network Function Virtualization (NFV), DevOps, Containers
  • App Economy:
    User Expectations and Agility
  • Internet of Things:
    If it isn't connected, don't bother ...
  • Tech Unicorns:
    Low barrier to entry for disruptors
5 Stages of Grief:
  • Denial
  • Anger
  • Bargaining
  • Depression
  • Acceptance
Carl's 3 Step Approach to Network Programmability:phase 1:
  • Python
  • REST APIs
  • JSON/XML
  • git/GitHub
Phase 2:
  • Linux Skills
  • Ansible
  • Docker
  • NETCONF/YANG
Phase 3:
  • Linux Networking
  • Container Networking
  • NFV
As Needed:
  • Network Controllers
  • IOT Networking
  • Cloud Networking
  • NFV
  • "DevOps"
Carl has Embraced Programmability! (and got himself a new shirt
smile.gif
):Core Programming:
  • Python
  • REST APIs
  • JSON/XML
  • Linux Skills
  • Ansible (Puppet/Chef/etc)
  • git/GitHub
  • Docker
  • "DevOps
"New" Networking Stuff:
  • Network Controllers
  • NETCONF/YANG
  • Container Networking
  • Cloud Networking
  • Linux Networking
  • IOT Networking
  • NFV
Data Formats: Understanding and using JSON, XML and YAML:Importance of a Data Format:Know Your Audience:
  • The output of the show interfaces brief command was designed for a human to read.
  • Structured data easy to break down for code to go through
Common Data Formats in Programming - A human-readable data structure that applications use to store, transfer, and read data:
  • JSON:
    {
    "ietf-interfaces:interface": {
    "name": "GigabitEthernet2",
    "description": "Wide Area Network",
    "enabled": true,
    "ietf-ip:ipv4": {
    "address": [
    {
    "ip": "172.16.0.2"
    "netmask": "255.255.255.0"
    }
    ]
    }
    }
    }
  • XML:


    GigabitEthernet2
    Wide Area Network
    true


    172.16.0.2
    255.255.255.0



  • YAML:
    ---
    ietf-interfaces:interface:
    name: GigabitEthernet2
    description: Wide Area Network
    enabled: true
    ietf-ip:ipv4"
    address:
    - ip: 172.16.0.2
    netmask: 255.255.255.0
Common Elements in a Data Format:
  • Format Syntax
  • Objects Representation
  • Key / Value Notation
    • Values can be objects, lists, strings, numbers, boolean
  • Arrays or List Notation
  • {"priorities": [
    "fire",
    "water",
    "club"
    ]
    }
"Key" : "Value":
  • "Key" identifies/labels a set of data
  • Left side of the colon
  • Inside of "quotes"
  • {
    "name": "GigabitEthernet2",
    "description": "Wide Area Network",
    "enabled: true
    }
  • "Value" is the Data
  • Right side of colon
  • Can be:
    • String
    • Integer
    • Array/List
    • Bool
    • Object
cool.gif
 

PlAwAnSaI

Administrator
Demystify XML: XML - eXtensible Markup Language:
  • Designed for the Internet
  • Schema or namespace defines data model
  • surround elements for structure and layout
  • Key/Value representation:
    • value
  • Whitespace not significant
XML Object:
  • A related set of data surrounded by
  • An object can contain other objects or data entries
  • value contained within the object tags
XML List:
  • List of data:
    • Can be composed of XML objects
  • Repeated instances of for each element


  • 172.16.0.2
    255.255.255.0


    172.16.0.3
    255.255.255.0
Breakdown JSON: JSON - JavaScript Object Notation:
  • A data-interchange text format
  • Notated with { } for objects, [ ] for arrays
  • Key/Value representation:
    • "key": value
  • Whitespace not significant
JSON Object:
  • Data surrounded by { }
  • An object can contain other objects or data entries
  • Key/Value set separated by comma
  • No comma at the end!
JSON List:
  • List of data
    • Can be composed of JSON objects
  • Notated with brackets
  • Comma Separated
  • {
    "addresses": [
    {
    "ip": "172.16.0.2",
    "netmask": "255.255.255.0"
    },
    {
    "ip": "172.16.0.3",
    "netmask": "255.255.255.0"
    }
    ]
    }
Simplify YAML: YAML - "YAML Ain't Markup Language":
  • Minimalist format commonly used for configuration files
  • Whitespace indentation defines structure
    • No commas
  • Key/Value representation
    • key: value
YAML Object:
  • Related set of data at the common indentation level under name
  • An object can contain other objects or data entries
  • key: value pairs left aligned
YAML List:
  • List of data:
    • Can be composed of YAML objects
  • Uses "-" character to indicate a list element
  • ---
    addresses:
    - ip: 172.16.0.2
    netmask: 255.255.255.0
    - ip: 172.16.0.3
    netmask: 255.255.255.0
APIs are Everywhere... but what are they?:What is an API?:"It's a way for two pieces of software to talk to each other"Application Programming Interface (API)For a long time... Humans were the only users:
  • Software displays results in User Interface (UI)
  • User asks for data or takes action by interacting with UI
But what about when the user is another software system...:
  • Your Software System - Software returns results via API >
  • My Software System - Software asks for data or takes action by interacting with API >
The API is the User Interface for software systemsAPIs are sets of requirements that govern how one application can talk to another.An API is like an electrical outlet:What would it be like to power a hair dryer without an outlet?:
  • Open wall
  • Strip Wires
  • Splice wires together
  • Understand all the wires on the wall
The outlet is a service that conforms to specifications:
  • Sockets deliver 120 volts of alternating current (AC) operating at 60Hz
  • Sets expectation on behalf of consumer devices and provider
An API is like ...:An API (Application Programming Interface) is best thought of as a contract provided by one piece of computer software to another.APIs help developers create apps that benefit the end user:- Yelp asks for Map Data > Google Maps - returns map data via API > yelp > Users sees list of restaurants close to themAPIs are often referred to as "an engine of innovation." -- Programmable WebAPIs aren't scary... you already use them:Command Line Interface (CLI):Designed for Humans... so more a UI than API but ...:
  • Network Management Systems
  • Expect Scripts
  • Paramiko/Netmiko
  • NAPALM
  • #!/usr/bin/expect -f

    send "conf tn"
    expect "(config)#"

    send "hostname my_switchn"
    expect "(config)#"
    send "ntp server 10.10.10.101n"
    expect "(config)#"
    send "ip domain-name domain.intran"
    expect "(config)#"

    send "endn"
    expect "#"
    send "write memn"
    expect "#"
Simple Network Management Protocol (SNMP):
  • "designed as a programmatic interface between management applications and devices"
    tools.ietf.org/html/rfc3535
  • Widely used for monitoring
  • Limited use for configuration
  • Network Management Systems primary consumer
Other APIs out there:Simple Object Access Protocol (SOAP):
  • Mature standard designed by Microsoft
  • Used to build "Web Services" (software available over the internet)
  • Typically uses HTTP, and dependent on XML
  • Sometimes considered complex and rigid
  • SOAP Web Service Communications:
    Messaging Client < HTTP : SOAP Implementation : SOAP Message > SOAP Service
Representational State Transfer (REST):
  • API framework intended to build simpler web services than SOAP
  • Another use for the HTTP protocol
  • Popular due to performance, scale, simplicity, and reliability
  • Technically an API framework
  • GET, POST, PUT, DELETE
XML-RPC and JSON-RPC:
  • Simple frameworks for communicating over HTTP
  • RPC = Remote Procedure Call
    • When one system requests another system to execute code
  • Offer XML and JSON data formats respectively
  • HTTP POST
    REQUEST BODY:
    [
    {
    "jsonrpc": "2.0",
    "method": "cli",
    "params":
    {
    "cmd": "show version",
    "version": 1
    },
    "id": 1
    }
    ]
NETCONF (NETwork CONFiguration) Protocol:
  • Designed as replacement for SNMP
  • Standardized in 2006 / Updated 2011
  • Leverages SSH and XML
  • Defines transport and communication
    • Titled coupled to YANG for data
  • NETCONF Communications:
    Manager < NETCONF : XML : YANG Data > Agent
  • XML:
    • Content | Configuration / Operational Data |
    • Operations | Actions to Take | , , , etc
    • Messages | Remote Procedure Call (RPC) | ,
  • Transport | TCP/IP Method | SSH
RESTCONF Protocol:
  • Provide REST API like interface to network
  • Standardized in 2017
  • Supports XML and JSON
  • Defines transport and communication
    • Titled coupled to YANG for data
  • Content | Configuration / Operational Data | XML or JSON
  • Operations | Actions to Take | GET, POST, PUT, PATCH, DELETE
  • Transport | TCP/IP Method | HTTP
cool.gif
 

PlAwAnSaI

Administrator
HTTP is for more than Web Browsing:What is REST?: Just Another Use for the HTTP Protocol
  • Representational state transfer (REST)
  • API framework built on HTTP
  • APIs often referred to as web services
  • Popular due to performance, scale, simplicity, and reliability
  • GET, POST, PUT, DELETE
Requests and Response, the REST API Flow:
  • Human - HTTP REQUEST GET http://devvie/api/hello >
  • Human < HTTP RESPONSE 200 OK JSON -
A Look Under the Hood at REST?:The URI: What are you Requesting?:http://maps.googleapis.com/maps/api/geocode/json?address=sanjose
  • http:// or https://
    • Define whether secure or open http
  • Server or Host: maps.googleapis.com
    • Resolves to the IP and port to connect to
  • Resource: /maps/api/geocode/json
    • The location of the data or object of interest on the server
  • Parameters: ?address=sanjose
    • Details on the scope, filter, or clarify a request. Often optional.
HTTP Methods: What to do?:HTTP Verb | Typical Purpose (CRUD) | Description
  • POST | Create | Used to create a new object or resource.
    Example: Add new book to library
  • GET | Read | Retrieve resource details from the system.
    Example: Get list of books from the library
  • PUT | Update | Typically used to replace or update a resource. Can be used to modify or create.
    Example: Update the borrower details for a book
  • PATCH | Update | Used to modify some details of a resource.
    Example: Change the author of a book
  • DELETE | Delete | Remove a resource from the system.
    Example: Delete a book from the library.
Response Status Codes: Did it work?:Status Code | Status Message | Meaning
  • 200 | OK | All looks good
  • 201 | Created | New resource created
  • 400 | Bad Request | Request was invalid
  • 401 | Unauthorized | Authentication missing or incorrect
  • 403 | Forbidden | Request was understood, but not allowed
  • 404 | Not Found | Resource not found
  • 500 | Internal Server Error | Something wrong with the server
  • 503 | Service Unavailable | Server is unable to complete the request
Headers: Details and meta-data:Header | Example Value | Purpose
  • Content-Type | application/json | Specify the format of the data in the body
  • Accept | application/json | Specify the requested format for returned data
  • Authorization | Basic dmFncmFudDp2YWdyYW50 | Provide credentials to authorize a request
  • Date | Tue, 25 Jul 2017 19:26:00 GMT | Date and time of the message
  • Used to pass information between client and server
  • Included in both REQUEST and RESPONSE
  • Some APIs will use custom headers for authentication or other purposes
Data: Sending and Receiving:
  • Contained in the body
  • POST, PUT, PATCH requests typically include data
  • GET responses will include data
  • The format typically JSON or XML:
    • Check "Content-Type" header
    {
    'title': 'Hamlet',
    'author': 'Shakespeare'
    }
HTTP Authentication and Security:
  • None: the Web API resource is public, anybody can place a call.
  • Basic HTTP: a username and password are passed to the server in an encoded string:
    • Authorization: Basic ENCODEDSTRING
  • Token: a secret generally retrieved from the Web API developer portal. Keyword (ie token) is API dependent:
    • Authorization: Token aikasf8adf9asd9akasdf0asd
  • OAuth: a Standard framework for a flow to retrieve an access token from an Identity Provider:
    • Authorization: Bearer 8a9af9adadf0asdf0adfa0af
  • Authorization can be short-lived and require refreshing of tokens
Some REST Examples:The Internet Chuck Norris Database:DevNet$ curl api.icndb.com/jokes/random
{
"type": "success",
"value": {
"id": 201,
"joke": "Chuck Norris was what Willis was talkin' about.",
"categories": [ ]
}
}
DevNet$ curl api.icndb.com/jokes/random?limitTo=nerdy
{
"type": "success",
"value": {
"id": 537,
"joke": "Each hair in Chuck Norris's beard contributes to making the worlds largest DDOS.",
"categories": [
"nerdy"
]
}
}
  • No authentication needed
  • Well constructed API with many options
Network Programmability with RESTCONF:The Request:DevNet$ curl -vk
-u root:cisco123
-H 'accept: application/yang-data+json'
https://10.10.20.21/restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet2

> GET /restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet2 HTTP/1.1
> Host: 10.10.20.21
> User-Agent: curl/7.51.0
> accept: application/yang-data+json
> authorization: Basic dmFncmFudDp2YWdyYW50
  • -u provides user:password for Basic Authentication
  • -H to set headers
  • Lines beginning with ">" indicate Request elements
  • Lines beginning with "
 

PlAwAnSaI

Administrator
API Collections:
  • Save and Organize API Calls into Collections
Using Environments:Variables Make Requests Reusable and Flexible:
  • Never good to hardcode details
  • What if you want to connect to different host?
  • What if credentials change?
Variables Make Requests Reusable and Flexible:
  • Variables References:
    • {{apic}}
    • {{username}}
    • {{password}}
Managing Environments:
  • Create any number of environments needed
  • Change between environments with a drop-down list
  • Add as many variables as needed
  • Reference anywhere with {{variable name}} syntax
Setting Environment Variables Dynamically:
  • What about when info from one request is needed in another?
  • Manually copying/pasting slow and error-prone
  • Manually updating environment variables is slow and awkward
  • Login Response:
    {
    "response": {
    "serviceTicket": "ST-6862-5DmKf5FrP0S4bSjy9rDM-cas",
    "idleTimeout": 1800,
    "sessionTimeout": 21600
    },
    "version": "1.0"
    }
  • Device List Request:
    > Network Device List
    4.jpg
"Tests" Enable Dynamic Environment Variables:
  • Each API Request offers both pre and post actions:
    • Pre -> Pre-request Script
    • Post -> Tests
  • Written in JavaScript
  • var jsonData = JSON.parse(responseBody);
    postman.setEnvironmentVariable("token",
    jsonData.response.serviceTicket);

    1c7b894767141ab34.jpg
Postman to Code!:You'll eventually want to write some code...:
  • Postman great for testing and validating APIs
  • But it's about atomic actions
  • Business Logic, stringing APIs together, etc all need code
  • Jumpstart with auto-generated code by Postman
  • Many, many options for languages available
Full API Request to Code!:
  • Headers, payload data, and URI all included
  • Environment variables are translated
  • A great starting point, but expect to edit and update

    27013d44eb2634760.jpg
Python Language and Script Basics:Why Python and How to get it?:
  • Python is powerful... and fast;
    plays well with others;
    runs everywhere;
    is friendly & easy to learn;
    is Open.
    www.python.org/about
The Zen of Python by Tim Peters:
  • Simple is better than complex.
  • The complex is better than complicated.
  • Special cases aren't special enough to break the rules.
  • Now is better than never.
  • Although never is often better than *right* now.
  • If the implementation is hard to explain, it's a bad idea.
  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • A flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!
Why Python for Network Engineers:
  • Readable and easy to learn
  • Widely available and Open Source
    • Windows, Mac, Linux
    • Routers & Switches
  • Many relevant code samples
  • Lots of training resources
How to get Python?
  • Might already have it
  • python.org/downloads
  • Package Management Tools
    • Example: Homebrew for Mac
      • brew install python2
      • brew install python3
    DevNet$ python -version
    Python 2.7.12
Breaking Down Python Code:example1.py:
  • Script Structure and Format
  • Importing and using packages
  • Variable declaration and usage
  • Function creations and usage
  • Basic Error Handling
  • # Entry point for program
    if _name_ == '_main_':
    # Retrieve command line input
    try:
    input = float(sys.argv[1])
    except (IndexError, ValueError) as e:
    # Indicates no command line parameter was provided
    print("You must provide a number as a parameter to this script")
    print("Example: ")
    print(" python example1.py 12")
    sys.exit(1)

    # Double the provided number and print output
    answer = doubler(input)
    print(answer)
  • In JSON in the payload are authentication credentials sent in a Cisco APIC REST API authorization request.
    www.cisco.com/c/en/us/td/docs/switches/datacenter/aci/apic/sw/2-x/rest_cfg/2_1_x/b_Cisco_APIC_REST_API_Configuration_Guide.html
  • OpenFlow automatically determines network forwarding rules and OpenFlow interfaces with the management plane.
Fundamentals of Open SDN and OpenFlow:
What is "Open?":
  • Open Standards:
    • BGP, VLAN, VxLAN
    • OpenFlow, I2RS, NetConf, YANG, OpFlex
  • Open Source Software:
    • OpenStack, OVS, OpenDaylight
    • Neutron
  • APIs and SDKs
  • Open Hardware:
    • Open Compute Project
  • cloudstack - Open Source Cloud Computing project
  • ETSI - ETSI SGI on "Network Function Virtualization"
  • IEEE - 802.1 Overlay Networking Projects
  • IETF:
    • Overlay Working Groups:
      NVO3, L2VPN, TRILL, L3VPN, LISP, PWE3
    • API Working Groups/BOFs:
      NETCONF, ALTO, CDNI, XMPP, SDNP, I2AEX
    • Controller Working Groups:
      PCE, FORCES
    • New working group:
      I2RS - Interface to the Routing System
  • IRTF - SDN WG
  • ITU
  • ONF (Open Networking Foundation) - Technical Advisory Group, Working Groups: Config, Hybrid, Extensibility, Futures/FPMOD/OF2.0
  • ONRC (Open Network Research Center) at Stanford University
  • Open Daylight: ODL Controller
  • OpenStack: Neutron (a.k.a. Quantum)
  • MEF
  • W3C
SDN Protocols: > Application Frameworks, Management Systems, Controllers, ...
  • Device:
    • Operating Systems - Cisco IOS / NX-OS / IOS-XR
    • BGP Diameter Radius SNMP ...
    • Cisco API & Agent Infrastructure (Chef, Puppet, YANG, etc.) > onePK > NETCONF
  • Forwarding:
    • BGP Diameter Radius SNMP ...
    • OpenFlow - ONF
  • Control:
    • BGP Diameter Radius SNMP ...
    • I2RS - IETF
  • Network Services:
    • BGP Diameter Radius SNMP ... > "Protocols"
    • PCEP - IETF
    • BGP-LS/FS - IETF
  • Orchestration:
    • OpenStack > Neutron
  • Management:
    • OMI
    • Puppet
    • NETCONF - IETF
    • ...
cool.gif
 
Top