Weitere ähnliche Inhalte Ähnlich wie Возможности интерпретатора Python в NX-OS (20) Mehr von Cisco Russia (20) Kürzlich hochgeladen (20) Возможности интерпретатора Python в NX-OS2. 2
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Cisco Support Community – Expert Series Webcast
Сегодня на семинаре Эксперт Cisco TAC Антон Тугай расскажет о тенденциях в области Cisco SDN и существующих решениях на данный момент.
Антон Тугай
Инженер центра
технической поддержки
Cisco TAC в Брюсселе
3. 3
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Технические Эксперты
Тема: Возможности интерпретатора Python в NX-OS
Дата проведения вебинара: 21 октября 2014 года
Борис Берлог
Инженер центра технической поддержки Cisco TAC в Брюсселе
Александр Нестеров
Инженер центра технической поддержки Cisco TAC в Брюсселе
4. 4
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Спасибо, что посетили наш вебинар сегодня
Сегодняшняя презентация включает опросы аудитории
Пожалуйста, участвуйте! 5. 5
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Спасибо, что присоединились к нам сегодня
Скачать презентацию Вы можете по ссылке:
https://supportforums.cisco.com/ru/document/12173321 7. 7
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Вопрос №1
Сталкивались ли вы уже с Openflow / SDN / onePK
a)Нет, не слышал ничего
b)Слышал о существовании но не вникал о чем это
c)Слышал, интересовался, имею представление
d)Уже использовал или ближайшее время планируется запуск, внедрение
e)Куда я попал?
8. 8
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Cisco Support Community – Expert Series Webcast
Антон Тугай
Инженер центра технической поддержки Cisco TAC в Брюсселе
Октябрь, 2014
Возможности интерпретатора Python в NX-OS 9. 9
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Несколько слов о Python
Интеграция Python в NX-OS
Примеры и демонстрация
Содержание 10. 10
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Несколько слов о Python
11. 11
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Where does the name python come from ?
Trivia! 12. 12
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Python is an interpreted programming (scripting) language
Available for Linux, Windows, Mac
Two common versions: 2.7(x) and 3.3(x)
2.7 more widely used than 3.3 at the time of writing
Python code is not compiled into standalone binary
It’s either interpreted (interactive shell) or translated into byte code and executed by Python VM
Code can be packaged as a “frozen binary” and executed on systems that don’t have Python installed
the Python VM is packaged within the frozen binary (using py2exe, pyinstaller or freeze)
Basics 13. 13
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Python home page
http://www.python.org/
Major Releases
Python 3.2.2 September 4, 2011
Python 3.1.4 June 11, 2011
Python 3.0.1 February 13, 2009
Python 2.7.2 June 11, 2011
Python 2.6.7 June 3, 2011
Python 2.5.4 December 23, 2008
Python 2.4.6 December 19, 2008
Python 2.3.7 March 11, 2008
Python 2.2.3 May 30, 2003
Python 2.1.3 April 8, 2002
Python 2.0.1 June 2001
Python 1.6.1 September 2000
Python Distributions
2.7.x is probably the version most frequently used today; this slide deck focuses primarily on 2.7 14. 14
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Python is an interpreted language
no pre-compile step as in Java and C++
each time Python code is run it is interpreted afresh
code changes can be very quickly made and tested
code can also be entered interactively
can dynamically construct Python code
For example in the form of a string and execute it directly
What about performance?
(much) slower than compiled C/C++ .. but also much more flexible
Good enough for most cases
Very large projects such as Openstack are implemented in Python
Modules to measure (profile) performance exist
Python is interpreted 15. 15
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
When executing Python instructions, Python internally compiles the source into a format called byte code
This is meant to speed up execution
This process is hidden from the programmer
You will now and then notice .pyc files automatically created in your folders (depending if Python has write access)
Next time you run your code, assuming it hasn’t been modified, Python skips the compilation step and directly runs the byte code inside the Python VM
The Python VM is Python’s runtime engine. It always comes with any installation of Python
Note: VM does not mean a VMware VM here!
Byte code compilation 16. 16
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
If you are used to other programming languages that are compiled, you should know there is a significant difference in terms of error checking with interpreted languages
Python checks errors at runtime
This means your code can contain errors such as
if name == ‘Foobar': print repeeeet(name) else: print repeat(name)
as long as name is not Foobar the error won’t get caught!
Keep that in mind, you will get caught!
Interpreted code: error checking 17. 17
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Be aware that Python is case sensitive
A and a are different variables
We’re going to explore variables in a bit
Python programs typically have the .py extension
Run using python <code.py> or python –i <code.py>
In Linux, you can set the execute bit and the proper shebang
typically, let the shell figure out which Python to use with this shebang: #!/usr/bin/env python
Python is case-sensitive 18. 18
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
You MUST indent code blocks in Python
Keep this rule in mind, it will catch you almost inevitably if you are already used to other programming languages
There are no curly braces to delimitate code blocks
Code blocks are identified with a colon and indentation
Prefer white spaces to tabs for indentation
Four white spaces is the preferred de-facto standard
http://legacy.python.org/dev/peps/pep-0008/#indentation
Indentation is mandatory 19. 19
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
The hash # sign indicates comments follow
Usually ok for short comments
Can start a new line or be used at the end of a line
Comments included at the beginning of your code appear when invoking help(yourscript):
Comments 20. 20
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Your code should contain comments
They should be relatively short and to the point
Comments should say why you are doing what you are doing
The code already says how; why you did things in a certain way is more important
Too many comments hurt readability though and require maintenance – find the right balance
Sidenote: should you write comments? 21. 21
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Why Python?
• CLI has no language structures (loops, conditions), Python provides that.
• Established, Modern and Powerful, Clean, lots of libraries.
TCL: less well-known, archaic, not cool.
Perl: well-known, but hacky, not object-oriented.
• Applications
Embedded Event Manager (EEM)
Power-On Auto-Provisioning (POAP)
Create “Super Commands”
Quick, Interactive, Automation.
22. 22
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Python Integration Overview
•Python Version 2.7.2
Interactive Mode
Non-interactive Mode (run scripts)
•Enhanced python: new function: cli(“cli-command”)
For show commands, 3 formats:
oReturn classical cli output (raw string)
oReturn a python dictionary (associative array)
oDirect print to stdout (practical when “playing” interactively)
•Python Exception Handling
Syntax Errors
Backend Errors
•Sandbox (no linux shell access, except allowed cases) 23. 23
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Интеграция Python в NX-OS
24. 24
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Native python interpreter on nexus
Ability to run python scripts on the nexus switch.
Provides ability to execute CLI commands from your python script.
Python scripts can parse CLI outputs and perform conditional actions (e.g syslog, shut/no shut, logging etc.)
Integration with EEM.
Call a different python script from a script
Lots of python modules available to import in your code.
No license needed!
No license needed
Native Python Available from: Nexus 5000 – 5.2(1)N1(1) Nexus 6000 – day 1 Nexus 7000 – 6.1(2) Nexus 9000 – day 1
Python version :
Nexus 5000 – 2.7.2
Nexus 6000 – 2.7.2
Nexus 7000 – 2.7.2
Nexus 9000 – 2.7.5 25. 25
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Invoking Python on Nexus 7K-5K
Nexus supports Python v2.7.2 version in 2 modes
ointeractive mode
o non interactive (script) mode
Interactive Mode
switch# python
Copyright (c) 2001-2012 Python Software Foundation; All Rights Reserved
switch# >>> print "hello world“
hello world
switch# >>> exit()
Non Interactive (script) Mode
Switch # source crc.py
----------------------------------------- -------
Started running CRC checker script
finished running CRC checker script
----------------------------------------- --------
Switch # dir bootflash:scripts
946 Oct 30 14:50:36 2013 crc.py
7009 Sep 19 10:38:39 2013 myScript.py
Type python to enter interactive python interpreter
How to call a python script on nexus 7000. crc.py script will be covered later in the slides
bootflash:scripts directory is the default script directory. 26. 26
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Available on N3K, N5K, N6K, N7K in “recent” releases
Available on N9K “standalone” at FCS
Just type “python” at the prompt
Then import cisco and import cli (N9K)
Python interpreter on NxOS 27. 27
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Unfortunately at the time of writing, Python on NXOS isn’t exactly similar across all Nexus platforms
The N9K is leading the effort – modules were simplified and cleaned up, XML output is being flattened for several commands
A significant difference between the N9K and the other platforms is how you invoke CLI commands. On the N9K you import cli and you get three functions: cli, clid and clip
cli.cli returns a string
cli.clid returns a JSON string
cli.clip returns print-friendly CLI output
Not platform independent 28. 28
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
How is Python integrated? (1/2)
CLI Interpreter
Python Interpreter
Operator
Console/telnet/ssh
Other nxos component
(bgp, osfp, …)
MTS
VSH
Switch from CLI to Python Interpreter
o Interactive: python / exit
o Non-interactive: source <file>
However, In Python Interpreter,
? and <tab> (online help)
operate on CLI parse-tree
py
exit
Cli() 29. 29
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
How is Python integrated? (2/2)
CLI Interpreter
Python Interpreter
Operator
Console/telnet/ssh
Other nxos component
(bgp, osfp, …)
MTS
VSH
•All regular python commands
o May be crippled by sandbox
o to block potentially malicious calls
• New python command “cli()”
o Run cli commands in python
• e.g, cli("show version")
o Takes cli command arg as a string
o Executes the cli command through
• cli interpreter
o Returns results as a string or
• dictionnary
o
Filtered by sandbox
Results as a string
CLI commands as a string
Execution 30. 30
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
switch# show clock
23:54:55.872 UTC Wed May 16 2012
switch# python -- enter python interpreter (adding >>> or ... to prompt)
switch# >>> cli(“conf term ; interface loopback 1”)
switch(config-if)# >>> cli(“ip address 1.1.1.1/24”)
switch(config-if)# >>> cli(“exit”) -- exit the cli interface mode
switch(config)# >>> cli(“exit”) -- still in python interp mode
switch# >>> i=0
switch# >>> while i<8: -- composite command -> ‘more input’ prompt (...)
switch# ... i=i+1
switch# ... cmd = "show module %i" % i
switch# ... r=clid(cmd)
switch# ... if "TABLE_modinfo/model" in r.keys():
switch# ... if r["TABLE_modinfo/model"] == "Nurburgring":
switch# ... print "got a racer in slot %d" % i
switch# ... – empty input to indicate end of loop
got a racer in slot 3
switch# >>> exit -- return to cli interpreter
switch# 31. 31
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
switch# python -- create python interpreter
switch# >>> i = 2
switch# >>> print “var i = %d” % i
var i = 2
switch# >>> cli(“configure terminal”)
switch(config)# >>> blabla
switch(config)# >>> exit -- destroy python interpreter
switch# - cli interp still at exec mode (“conf t” is lost)
switch# python -- new python interp
switch# >>> print “var i = %d” % i -- previous python cli mode and vars gone
Error: variable ‘i’ undefined.
switch# >>> exit
switch# conf t ; inter lo 1
switch(config-if)# python -- new python interp
switch(config-if)# >>> -- inherits the cli mode (forked from cli).
Python is forked from vsh ->
•No state is preserved between two python invocations
•CLI mode is lost permanently when exiting python 32. 32
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
CLI Formats (1/2)
string = cli (“cli-command”) -- returns cli output as a string
dictionary = clid (“cli-command”) -- returns a dictionary (if xml output)
clip (“cli-command”) -- returns void, prints to stdout
Three formats:
switch# >>> cli("conf ; interface loopback 1")
Enter configuration commands, one per line. End with CNTL/Z.
switch(config-if)# >>> clip('where detail‘)
mode: conf
interface loopback1
username: root
vdc: switch
routing-context vrf: default
switch(config-if)# >>> cli('where detail')
'x1b[00m mode: confn interface loopback1n username: rootn vdc: switchn routing-context vrf: defaultn'
switch(config-if)# >>> r = cli('where detail') ; print r
(same output as clip() above!) 33. 33
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
switch(config-if)# >>> i=0
switch(config-if)# >>> while i<3:
switch(config-if)# ... i=i+1
switch(config-if)# ... cli('ip addr 1.1.1.1/24')
switch(config-if)# ...
switch(config-if)# >>> cli('end')
switch# >>> r = clid('show version')
switch# >>> for k in r.keys():
switch# ... print "%30s" % k, " = %s" % r[k]
switch# ...
cpu_name = Intel(R) Xeon(R) CPU
rr_sys_ver = 6.2(0.110)
manufacturer = Cisco Systems, Inc.
isan_file_name = bootflash:///full
rr_ctime = Wed May 16 02:40:57 2012
proc_board_id = JAF1417AGCB
bios_cmpl_time = 02/20/10
kickstart_ver_str = 6.1(1) [build 6.1(0.292)] [gdb]
isan_tmstmp = 05/16/2012 02:26:02
switch# >>> exit 34. 34
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
switch# show file bootflash:scripts/test1.py
#!/bin/env python
i=0
while i<3:
r=clip('show version')
uptime_name='/@/show/version/__readonly__/kern_uptm_secs'
print uptime_name, r[uptime_name]
clid('sleep 1')
i=i+1
switch# source test1.py -- default directory is /bootflash/scripts
/@/show/version/__readonly__/kern_uptm_secs 36
/@/show/version/__readonly__/kern_uptm_secs 38
/@/show/version/__readonly__/kern_uptm_secs 40
switch#
Default directory of scripts
Invoke python 35. 35
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
switch(config)# >>> cli("interface loop 1")
switch(config-if)# >>> cli("ip address 1234.1.1.1/24")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
cisco.cli_syntax_error: % Invalid ip address at '===>' marker:
% ip address 123===>4.1.1.1/24
switch(config-if)# >>> try: cli("ip address 1234.1.1.1/24")
switch(config-if)# ... except: print sys.exc_type, sys.exc_value
switch(config-if)# ...
<class 'cisco.cli_syntax_error'> % Invalid ip address at '===>' marker:
% ip address 123===>4.1.1.1/24
switch(config-if)# >>> try: cli("ip address 1.1.1.1/24")
switch(config-if)# ... except: print sys.exc_type, sys.exc_value
switch(config-if)# ...
switch(config-if)# >>> cli("interface loopback 2")
switch(config-if)# >>> try: cli("ip address 1.1.1.1/24")
switch(config-if)# ... except: print sys.exc_type, sys.exc_value
switch(config-if)# ...
<class 'cisco.cli_execution_error'>
% 1.1.1.1/24 overlaps with address configured on loopback1
switch(config-if)# >>> 36. 36
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
switch# python
Copyright (c) 2001-2012 Python Software Foundation; All Rights Reserved
switch# >>> import os
switch# >>> os.getcwd()
'/bootflash'
switch# >>> os.chdir("/isan/bin")
Permission denied. Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 13] Permission denied: '/isan/bin'
switch# >>> os.system("cd /isan/bin")
system(cd /isan/bin): rejected!
-1
switch# >>> f=open("/isan/bin/vsh", "r")
Permission denied. Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 13] Permission denied: '/isan/bin/vsh'
switch# >>> f=open("/bootflash/alias", "r")
switch# >>>
•Block potentially harmful function calls 37. 37
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
An “online help protocol” allows script to provide online help, man-page and context sensitive variants
switch# source ? abc No help script is not supporting the online help protocol cgrep 'context grep': shows matching line plus the context lines (to be used behind a pipe, for show-run type of output) Example of context for 'ip address 1.1.1.1/24': ‘eth 2/1’ find-if Find interfaces that match selected attribute values (from 'show intf br') ntimes Runs specified command specified numbers of times redo-history This is run a list of commands from the history again show-if Show selected interface attributes show-version A better 'show version' sys/ Directory here you find example scripts, packaged in image switch# source ntimes ? filename can be abbridged if unique (or tabbed) arg1: the command, in quotes arg2: number of times to run the commands <CR> > Redirect it to a file >> Redirect it to a file in append mode | Pipe command output to filter 38. 38
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
The script is called with the following argument: __cli_script.*help __cli_script_help : request to return a one line description of the script’s purpose __cli_script_args_help : request to return help for arguments, filename is passed as first argument, as well as any arguments entered so far __cli_script_args_help_partial: the last argument is ‘partial’. E.g. “token?” instead of “token ?”. Argument help return formats: classical (“type|description” left|right side”): print "ftp|Use ftp for file transfer protocol" print "scp|Use scp for file transfer protocol" exit(0) Man Page style (simpler to implement, but no tabbing). print "__man_page" print " whatever…“ 39. 39
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Python Introspection on Cisco Extension >>> import cisco >>> cisco.__doc__ 'contains commands that integrate with Cisco CLI' >>> dir(cisco) ['__doc__', '__name__', '__package__', 'cli', 'clid', 'clip'] >>> cisco.cli.__doc__ 'execute a cli command, return the lines of output as char*' >>> cisco.clid.__doc__ 'execute a cli command, return name/value pairs (d: dictionary)' >>> cisco.clip.__doc__ 'execute a cli command, just dump to stdout, return void to python (p: print)' >>> >>> [(a,type(cisco.__getattribute__(a))) for a in dir(cisco)] [('__doc__', <type 'str'>), ('__name__', <type 'str'>), ('__package__', <type 'NoneType'>), ('cli', <type 'builtin_function_or_method'>), ('clid', <type 'builtin_function_or_method'>), ('clip', <type 'builtin_function_or_method'>)] >>> 40. 40
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Backgrounding a script
switch# source background sleep 100
switch# source background sleep 50
switch# show background
username . terminal pid start time script args ...
root . . pts/0 7687 03:31 00:00:00 sleep.py 90 .
root . . pts/0 7696 03:31 00:00:00 sleep.py 50 .
switch# kill background ?
WORD Background script to terminate, by process-id or just
a regex matching any line from 'show background' output
switch# kill background 7687
switch# show background
username . terminal pid start time script args ...
root . . pts/0 7696 03:31 00:00:00 sleep.py 50 .
switch#
switch# exit
Linux(debug)# su john
switch# kill background 7696
bash: line 1: kill: (7696) - Operation not permitted
switch#
41. 41
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Expect
switch# python
Copyright (c) 2001-2012 Python Software Foundation; All Rights Reserved
switch# >>> import pexpect
switch# >>> child=pexpect.spawn("vsh") -- only vsh allowed
switch# >>> child.sendline("show clock")
11
switch# >>> child.expect(".*2012")
0
switch# >>> print child.after
show clock
switch# show clock
03:44:12.620 UTC Wed Sep 26 2012
switch# >>> 42. 42
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Importing Python Libraries Containing cli()
You need to import the ‘cisco’ module
(done automatically by ‘python’ or ‘source’ command, but not by ‘import’ command).
File time.py:
from cisco import cli
def show_clock:
cli(“show clock”)
File stuff.py:
import time
time.show_clock() 43. 43
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Вопрос №2
После полученной информации ваш интерес к SDN
a)У меня и так все работает, не хочу усложнять и строить космический корабль
b)Интересно, возможно протестирую в свободное время
c)Заинтересован, займусь изучением вопроса и попробую запустить
d)У нас уже используется либо проводятся тесты
e)До сих пор не понимаю о чем идет речь
44. 44
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Вопрос №3
О чем было бы интересно узнать на следующем вебинаре о SDN
a)Контроллерные решения на основе Cisco XNC
b)Cisco и OpenStack совместные решения
c)APIC / ACI / Insieme / Nexus 9000
d)VxLAN
45. Отправьте свой вопрос сейчас!
Используйте панель Q&A, чтобы задать вопрос. Эксперты ответят на Ваши вопросы. 46. Получить дополнительную информацию, а также задать вопросы эксперту в рамках данной темы Вы можете на странице, доступной по ссылке:
https://supportforums.cisco.com/community/russian/expert-corner
Вы можете получить видеозапись данного семинара и текст сессии Q&A в течении ближайших 5 дней по следующей ссылке
https://supportforums.cisco.com/community/russian/expert-corner/webcast
47. 47
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
Вебинар на русском языке Тема: Базовая настройка Device Provisioning и отладка основных проблем при использовании Cisco TMS Provisioning Extension
во вторник, 25 ноября, в 12.00 мск
Присоединяйтесь к эксперту Cisco
Михаилу Щекотилову
В рамках сессии будет проведена демонстрация базовой настройки Device Provisioning на Cisco VCS и TMS, а также разобраны основные ошибки, которые при этом встречаются, и показаны методы и инструменты для их отладки.
48. 48
© 2013-2014 Cisco and/or its affiliates. All rights reserved. https://supportforms.cisco.com/community/russian
http://www.facebook.com/CiscoSupportCommunity
http://twitter.com/#!/cisco_support
http://www.youtube.com/user/ciscosupportchannel
https://plus.google.com/110418616513822966153?prsrc=3#110418616513822966153/posts
http://itunes.apple.com/us/app/cisco-technical-support/id398104252?mt=8
https://play.google.com/store/apps/details?id=com.cisco.swtg_android
http://www.linkedin.com/groups/CSC-Cisco-Support-Community-3210019
Newsletter Subscription: https://tools.cisco.com/gdrp/coiga/showsurvey.do?surveyCode=589&keyCode=146298_2&PHYSICAL%20FULFILLMENT%20Y/N=NO&SUBSCRIPTION%20CENTER=YES
49. 49
© 2013-2014 Cisco and/or its affiliates. All rights reserved.
•Русском https://supportforums.cisco.com/community/russian
•Испанском https://supportforums.cisco.com/community/5591/comunidad-de- soporte-de-cisco-en-espanol
•Португальском https://supportforums.cisco.com/community/5141/comunidade-de-suporte- cisco-em-portugues
•Японском http://www.csc-china.com.cn/