SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Downloaden Sie, um offline zu lesen
Возможности интерпретатора Python в NX-OS 
Anton Tugai 
Customer Support Engineer, Cisco TAC 
October, 2014
2 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Cisco Support Community – Expert Series Webcast 
Сегодня на семинаре Эксперт Cisco TAC Антон Тугай расскажет о тенденциях в области Cisco SDN и существующих решениях на данный момент. 
Антон Тугай 
Инженер центра 
технической поддержки 
Cisco TAC в Брюсселе
3 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Технические Эксперты 
Тема: Возможности интерпретатора Python в NX-OS 
Дата проведения вебинара: 21 октября 2014 года 
Борис Берлог 
Инженер центра технической поддержки Cisco TAC в Брюсселе 
Александр Нестеров 
Инженер центра технической поддержки Cisco TAC в Брюсселе
4 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Спасибо, что посетили наш вебинар сегодня 
Сегодняшняя презентация включает опросы аудитории 
Пожалуйста, участвуйте!
5 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Спасибо, что присоединились к нам сегодня 
Скачать презентацию Вы можете по ссылке: 
https://supportforums.cisco.com/ru/document/12173321
Присылайте Ваши вопросы! 
Используйте панель Q&A, чтобы задать вопрос. Наши эксперты ответят на них.
7 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Вопрос №1 
Сталкивались ли вы уже с Openflow / SDN / onePK 
a)Нет, не слышал ничего 
b)Слышал о существовании но не вникал о чем это 
c)Слышал, интересовался, имею представление 
d)Уже использовал или ближайшее время планируется запуск, внедрение 
e)Куда я попал?
8 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Cisco Support Community – Expert Series Webcast 
Антон Тугай 
Инженер центра технической поддержки Cisco TAC в Брюсселе 
Октябрь, 2014 
Возможности интерпретатора Python в NX-OS
9 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Несколько слов о Python 
Интеграция Python в NX-OS 
Примеры и демонстрация 
Содержание
10 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Несколько слов о Python
11 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Where does the name python come from ? 
Trivia!
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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Интеграция Python в NX-OS
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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 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 
© 2013-2014 Cisco and/or its affiliates. All rights reserved. 
Вопрос №2 
После полученной информации ваш интерес к SDN 
a)У меня и так все работает, не хочу усложнять и строить космический корабль 
b)Интересно, возможно протестирую в свободное время 
c)Заинтересован, займусь изучением вопроса и попробую запустить 
d)У нас уже используется либо проводятся тесты 
e)До сих пор не понимаю о чем идет речь
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
Отправьте свой вопрос сейчас! 
Используйте панель Q&A, чтобы задать вопрос. Эксперты ответят на Ваши вопросы.
Получить дополнительную информацию, а также задать вопросы эксперту в рамках данной темы Вы можете на странице, доступной по ссылке: 
https://supportforums.cisco.com/community/russian/expert-corner 
Вы можете получить видеозапись данного семинара и текст сессии Q&A в течении ближайших 5 дней по следующей ссылке 
https://supportforums.cisco.com/community/russian/expert-corner/webcast
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 
© 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 
© 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/
Спасибо за Ваше время Пожалуйста, участвуйте в опросе

Weitere ähnliche Inhalte

Was ist angesagt?

KVM/ARM Nested Virtualization Support and Performance - SFO17-410
KVM/ARM Nested Virtualization Support and Performance - SFO17-410KVM/ARM Nested Virtualization Support and Performance - SFO17-410
KVM/ARM Nested Virtualization Support and Performance - SFO17-410
Linaro
 
OPNFV Arno Installation and Validation Walk Through
OPNFV Arno Installation and Validation Walk ThroughOPNFV Arno Installation and Validation Walk Through
OPNFV Arno Installation and Validation Walk Through
OPNFV
 

Was ist angesagt? (20)

LF_OVS_17_Enabling hardware acceleration in OVS-DPDK using DPDK Framework.
LF_OVS_17_Enabling hardware acceleration in OVS-DPDK using DPDK Framework.LF_OVS_17_Enabling hardware acceleration in OVS-DPDK using DPDK Framework.
LF_OVS_17_Enabling hardware acceleration in OVS-DPDK using DPDK Framework.
 
Packet walks in_kubernetes-v4
Packet walks in_kubernetes-v4Packet walks in_kubernetes-v4
Packet walks in_kubernetes-v4
 
4. open mano set up and usage
4. open mano set up and usage4. open mano set up and usage
4. open mano set up and usage
 
Learn more about the tremendous value Open Data Plane brings to NFV
Learn more about the tremendous value Open Data Plane brings to NFVLearn more about the tremendous value Open Data Plane brings to NFV
Learn more about the tremendous value Open Data Plane brings to NFV
 
淺談 Live patching technology
淺談 Live patching technology淺談 Live patching technology
淺談 Live patching technology
 
KVM/ARM Nested Virtualization Support and Performance - SFO17-410
KVM/ARM Nested Virtualization Support and Performance - SFO17-410KVM/ARM Nested Virtualization Support and Performance - SFO17-410
KVM/ARM Nested Virtualization Support and Performance - SFO17-410
 
OPNFV Arno Installation and Validation Walk Through
OPNFV Arno Installation and Validation Walk ThroughOPNFV Arno Installation and Validation Walk Through
OPNFV Arno Installation and Validation Walk Through
 
Kubernetes Ingress 101
Kubernetes Ingress 101Kubernetes Ingress 101
Kubernetes Ingress 101
 
Fastsocket Linxiaofeng
Fastsocket LinxiaofengFastsocket Linxiaofeng
Fastsocket Linxiaofeng
 
OpenDataPlane Project
OpenDataPlane ProjectOpenDataPlane Project
OpenDataPlane Project
 
Lessons learned with kubernetes in production at PlayPass
Lessons learned with kubernetes in productionat PlayPassLessons learned with kubernetes in productionat PlayPass
Lessons learned with kubernetes in production at PlayPass
 
Kubernetes networking-made-easy-with-open-v switch
Kubernetes networking-made-easy-with-open-v switchKubernetes networking-made-easy-with-open-v switch
Kubernetes networking-made-easy-with-open-v switch
 
zebra & openconfigd Introduction
zebra & openconfigd Introductionzebra & openconfigd Introduction
zebra & openconfigd Introduction
 
3. configuring a compute node for nfv
3. configuring a compute node for nfv3. configuring a compute node for nfv
3. configuring a compute node for nfv
 
LF_OVS_17_IPSEC and OVS DPDK
LF_OVS_17_IPSEC and OVS DPDKLF_OVS_17_IPSEC and OVS DPDK
LF_OVS_17_IPSEC and OVS DPDK
 
BKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
BKK16-302: Android Optimizing Compiler: New Member Assimilation GuideBKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
BKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
 
Howto createOpenFlow Switchusing FPGA (at FPGAX#6)
Howto createOpenFlow Switchusing FPGA (at FPGAX#6)Howto createOpenFlow Switchusing FPGA (at FPGAX#6)
Howto createOpenFlow Switchusing FPGA (at FPGAX#6)
 
SGX Trusted Execution Environment
SGX Trusted Execution EnvironmentSGX Trusted Execution Environment
SGX Trusted Execution Environment
 
How Linux Processes Your Network Packet - Elazar Leibovich
How Linux Processes Your Network Packet - Elazar LeibovichHow Linux Processes Your Network Packet - Elazar Leibovich
How Linux Processes Your Network Packet - Elazar Leibovich
 
The Universal Dataplane
The Universal DataplaneThe Universal Dataplane
The Universal Dataplane
 

Ähnlich wie Возможности интерпретатора Python в NX-OS

Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
Kanchilug
 
CHX PYTHON INTRO
CHX PYTHON INTROCHX PYTHON INTRO
CHX PYTHON INTRO
Kai Liu
 
Python Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & TechPython Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & Tech
Ramanamurthy Banda
 

Ähnlich wie Возможности интерпретатора Python в NX-OS (20)

Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdf
 
Python_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdfPython_final_print_batch_II_vision_academy (1).pdf
Python_final_print_batch_II_vision_academy (1).pdf
 
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdfPython_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdf
 
Python_vision_academy notes
Python_vision_academy notes Python_vision_academy notes
Python_vision_academy notes
 
Python_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdfPython_final_print_vison_academy_9822506209.pdf
Python_final_print_vison_academy_9822506209.pdf
 
Module1-Chapter1_ppt.pptx
Module1-Chapter1_ppt.pptxModule1-Chapter1_ppt.pptx
Module1-Chapter1_ppt.pptx
 
Research paper on python by Rj
Research paper on python by RjResearch paper on python by Rj
Research paper on python by Rj
 
Python Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech PunePython Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech Pune
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
Cmpe202 01 Research
Cmpe202 01 ResearchCmpe202 01 Research
Cmpe202 01 Research
 
python unit2.pptx
python unit2.pptxpython unit2.pptx
python unit2.pptx
 
report on internshala python training
 report on internshala python  training  report on internshala python  training
report on internshala python training
 
Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Python
 
Python Developer Certification
Python Developer CertificationPython Developer Certification
Python Developer Certification
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
 
CHX PYTHON INTRO
CHX PYTHON INTROCHX PYTHON INTRO
CHX PYTHON INTRO
 
PyQt Application Development On Maemo
PyQt Application Development On MaemoPyQt Application Development On Maemo
PyQt Application Development On Maemo
 
Python Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & TechPython Programming Unit1_Aditya College of Engg & Tech
Python Programming Unit1_Aditya College of Engg & Tech
 

Mehr von Cisco Russia

Mehr von Cisco Russia (20)

Service portfolio 18
Service portfolio 18Service portfolio 18
Service portfolio 18
 
История одного взлома. Как решения Cisco могли бы предотвратить его?
История одного взлома. Как решения Cisco могли бы предотвратить его?История одного взлома. Как решения Cisco могли бы предотвратить его?
История одного взлома. Как решения Cisco могли бы предотвратить его?
 
Об оценке соответствия средств защиты информации
Об оценке соответствия средств защиты информацииОб оценке соответствия средств защиты информации
Об оценке соответствия средств защиты информации
 
Обзор Сервисных Услуг Cisco в России и странах СНГ.
Обзор Сервисных Услуг Cisco в России и странах СНГ.Обзор Сервисных Услуг Cisco в России и странах СНГ.
Обзор Сервисных Услуг Cisco в России и странах СНГ.
 
Клиентские контракты на техническую поддержку Cisco Smart Net Total Care
Клиентские контракты на техническую поддержку Cisco Smart Net Total CareКлиентские контракты на техническую поддержку Cisco Smart Net Total Care
Клиентские контракты на техническую поддержку Cisco Smart Net Total Care
 
Cisco Catalyst 9000 series
Cisco Catalyst 9000 series Cisco Catalyst 9000 series
Cisco Catalyst 9000 series
 
Cisco Catalyst 9500
Cisco Catalyst 9500Cisco Catalyst 9500
Cisco Catalyst 9500
 
Cisco Catalyst 9400
Cisco Catalyst 9400Cisco Catalyst 9400
Cisco Catalyst 9400
 
Cisco Umbrella
Cisco UmbrellaCisco Umbrella
Cisco Umbrella
 
Cisco Endpoint Security for MSSPs
Cisco Endpoint Security for MSSPsCisco Endpoint Security for MSSPs
Cisco Endpoint Security for MSSPs
 
Cisco FirePower
Cisco FirePowerCisco FirePower
Cisco FirePower
 
Профессиональные услуги Cisco для Software-Defined Access
Профессиональные услуги Cisco для Software-Defined AccessПрофессиональные услуги Cisco для Software-Defined Access
Профессиональные услуги Cisco для Software-Defined Access
 
Обнаружение известного вредоносного кода в зашифрованном с помощью TLS трафик...
Обнаружение известного вредоносного кода в зашифрованном с помощью TLS трафик...Обнаружение известного вредоносного кода в зашифрованном с помощью TLS трафик...
Обнаружение известного вредоносного кода в зашифрованном с помощью TLS трафик...
 
Промышленный Интернет вещей: опыт и результаты применения в нефтегазовой отрасли
Промышленный Интернет вещей: опыт и результаты применения в нефтегазовой отраслиПромышленный Интернет вещей: опыт и результаты применения в нефтегазовой отрасли
Промышленный Интернет вещей: опыт и результаты применения в нефтегазовой отрасли
 
Полугодовой отчет Cisco по информационной безопасности за 2017 год
Полугодовой отчет Cisco по информационной безопасности за 2017 год Полугодовой отчет Cisco по информационной безопасности за 2017 год
Полугодовой отчет Cisco по информационной безопасности за 2017 год
 
Годовой отчет Cisco по кибербезопасности за 2017 год
Годовой отчет Cisco по кибербезопасности за 2017 годГодовой отчет Cisco по кибербезопасности за 2017 год
Годовой отчет Cisco по кибербезопасности за 2017 год
 
Безопасность для цифровой экономики. Развитие продуктов и решений Cisco
Безопасность для цифровой экономики. Развитие продуктов и решений CiscoБезопасность для цифровой экономики. Развитие продуктов и решений Cisco
Безопасность для цифровой экономики. Развитие продуктов и решений Cisco
 
Cisco StealthWatch. Использование телеметрии для решения проблемы зашифрованн...
Cisco StealthWatch. Использование телеметрии для решения проблемы зашифрованн...Cisco StealthWatch. Использование телеметрии для решения проблемы зашифрованн...
Cisco StealthWatch. Использование телеметрии для решения проблемы зашифрованн...
 
Обеспечение бесперебойной работы корпоративных приложений в больших гетероген...
Обеспечение бесперебойной работы корпоративных приложений в больших гетероген...Обеспечение бесперебойной работы корпоративных приложений в больших гетероген...
Обеспечение бесперебойной работы корпоративных приложений в больших гетероген...
 
Новое поколение серверов Сisco UCS. Гиперконвергентное решении Cisco HyperFle...
Новое поколение серверов Сisco UCS. Гиперконвергентное решении Cisco HyperFle...Новое поколение серверов Сisco UCS. Гиперконвергентное решении Cisco HyperFle...
Новое поколение серверов Сisco UCS. Гиперконвергентное решении Cisco HyperFle...
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 

Возможности интерпретатора Python в NX-OS

  • 1. Возможности интерпретатора Python в NX-OS Anton Tugai Customer Support Engineer, Cisco TAC October, 2014
  • 2. 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
  • 6. Присылайте Ваши вопросы! Используйте панель Q&A, чтобы задать вопрос. Наши эксперты ответят на них.
  • 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/
  • 50. Спасибо за Ваше время Пожалуйста, участвуйте в опросе