Learning Python Week 6

The second half of this course includes some important content for improving your Python programming. In particular, Class6 on Functions and Namespaces, Class8 on Modules, and Class9 on Classes and Objects.

In this email of Learning Python we are going to cover the following:

I. Introduction Week6
video http://youtu.be/sjYBE6EWwuc
Length is 3 minutes

II. Functions, Part1
video http://youtu.be/i1MzASLYOZY
Length is 12 minutes

III. Namespaces
video http://youtu.be/r8U3_KkvKtw
Length is 10 minutes

IV. Functions, Part2
video http://youtu.be/pRaVagkh9l8
Length is 12 minutes

Additional content that you may be interested in

There is a good chapter on functions in “Learn Python the Hard Way” (I would stop after you finish, “What You Should See”).

Darren O’Connor has a blog on “Defined Functions – Python”.



Reference code for these exercises is posted on GitHub at:

1. Create a function that returns the multiplication product of three parameters–x, y, and z. z should have a default value of 1.
a. Call the function with all positional arguments.
b. Call the function with all named arguments.
c. Call the function with a mix of positional and named arguments.
d. Call the function with only two arguments and use the default value for z.
2. Write a function that converts a list to a dictionary where the index of the list is used as the key to the new dictionary (the function should return the new dictionary).

3a.Convert the IP address validation code (Class4, exercise1) into a function, take one variable ‘ip_address’ and return either True or False (depending on whether ‘ip_address’ is a valid IP). Only include IP address checking in the function–no prompting for input, no printing to standard output.

3b. Import this IP address validation function into the Python interpreter shell and test it (use both ‘import x’ and ‘from x import y’).

4. Create a function using your dotted decimal to binary conversion code from Class3, exercise1. In the function–do not prompt for input and do not print to standard output. The function should take one variable ‘ip_address’ and should return the IP address in dotted binary format always padded to eight binary digits (for example 00001010.01011000.00010001.00010111). You might want to create other functions as well (for example, the zero-padding to eight binary digits).

5. Write a program that prompts a user for an IP address, then checks if the IP address is valid, and then converts the IP address to binary (dotted decimal format). Re-use the functions created in exercises 3 and 4 (‘import’ the functions into your new program).



Class Outline

I. Introduction
A. Why write functions?

II. Functions Part1
A. Function with no parameters
1. Syntax and structure
2. Calling the function
3. Return value
4. Using the return value
5. Docstrings

B. Function with parameters
1. Syntax
2. Default values

C. Various ways of passing arguments to functions
1. Positional arguments
2. Named arguments
3. Mixing positional and named arguments

III. Python Namespaces
A. Functions create their own namespace
B. Name resolution order

IV. Functions Part2
A. Using lists and dicts as function arguments
B. Importing a function



Video Archive

Introduction and Some Questions
What is the Nature of Python
Interpreter Shell, Variables, and Assignment

Print and raw_input
Lists and Tuples

If Conditionals
For Loops
Passing Arguments into a Script

While Loops

Class Review (weeks 1 – 4)

Security operations and analytics platform architecture (SOAPA)

Security operations and analytics platform architecture (SOAPA)

Security information and event management (SIEM) systems have been around for a dozen years or so. During that timeframe, SIEMs evolved from perimeter security event correlation tools, to GRC platforms, to security analytics systems. Early vendors like eSecurity, GuardedNet, Intellitactics, and NetForensics, are distant memories; today’s SIEM market is now dominated by a few leaders: LogRhythm, McAfee (aka: Nitro Security), HP (aka: ArcSight), IBM (aka: QRadar), and Splunk.

Of course, there is a community of innovative upstarts that believe that SIEM is a legacy technology. They proclaim that log management and event correlation can’t keep up with the pace of cybersecurity today, thus you need new technologies like artificial intelligence, machine learning algorithms, and neural networks to consume, process, and analyze security data in real-time.


As an industry analyst, I should be waving my arms around madly, proclaiming that “SIEM is dead,” since that’s what those in my profession tend to do. Sorry, but I don’t think SIEM is dead at all. Instead, enterprise security operations and analytics requirements are forcing rapid consolidation into something new that ESG calls a security operations and analytics platform architecture (SOAPA).

Within SOAPA, SIEM -like functionality still plays a starring role, often aggregating analytics data into a common repository. But unlike the past, SIEM is one of several security tools within SOAPA, and these technologies must be designed for asynchronous cooperation so security analysts can quickly pivot across tools to find data and take action as they need to in real-time.

SOAPA is a dynamic architecture, meaning that new data sources and control planes will be added incrementally overtime. I do believe, however, that today’s SOAPA is built with SIEMs (or similar log management and search products/services) and:

  • Endpoint detection/response tools (EDR). Security analysts often want to dig deep into security alerts by monitoring and investigating host behavior so EDR (i.e. CarbonBlack, Countertack, CrowdStrike, Guidance Software, etc.) is an essential component of SOAPA.
  • Incident response platforms (IRPs). Aside from collecting, processing, and analyzing security data, cybersecurity professionals want to prioritize alerts and remediate problems as soon as possible. These requirements are giving rise to the rise of IRPs like Hexadite, Phantom, Resilient Systems (IBM), ServiceNow, and Swimlane.
  • Network security analytics. SIEM’s log analysis and EDR host behavior monitoring are complemented by flow and packet analysis in SOAPA, provided by vendors like Arbor Networks, Blue Coat/Symantec, Cisco (Lancope), RSA, etc.
  • UBA/machine learning algorithms. While these tools have received an inordinate degree of industry hype, there’s little doubt that machine learning will be baked into security analytics henceforth, thus vendors like Bay Dynamics, Caspeda (Splunk), Exabeam, Niara, Sqrrl, and Varonis should be included in SOAPA.
  • Vulnerability scanners and security asset managers. Part of security operations is knowing which alerts should be prioritized. These decisions must be driven by solid data from vulnerability management systems (i.e., Qualys, Rapid7, Tanium), and other tools that monitor the state of systems and network configurations (i.e., RedSeal, Skybox, Verodin, etc.).
  • Anti-malware sandboxes. This technology represents another key pivot point for understanding targeted attacks that may use zero-day malware. Sandboxes from FireEye, Fidelis, and Trend Micro are definitely part of SOAPA.
  • Threat intelligence. Enterprise organizations want to compare internal network anomalies with malicious “in-the-wild” activities so SOAPA extends to threat intelligence sources and platforms (i.e., BrightPoint [ServiceNow], FireEye/iSight Partners, RecordedFuture, ThreatConnect, ThreatQuotient, etc.).

Aside from the technologies themselves, here are a few other thoughts on SOAPA:

  1. Beyond data exchange between security tools, the next big innovation will be central SOAPA command-and-control for analytics and management (i.e., configuration management, policy management, etc.) of the security infrastructure.
  2. The market is already moving in SOAPA’s direction. Witness IBM’s acquisition of Resilient Systems for IRP, Splunk’s purchase of Caspida for UBA, and Elastic Search’s acquisition of Prelert.
  3. Now that McAfee is independent of Intel, look for it to invest in its enterprise security manager (i.e., Nitro). McAfee will also accelerate SOAPA technology integration with its own tools and ecosystem partners, and acquisitions aimed at filling architectural gaps.
  4. Given the central role that SIEM still plays in SOAPA, someone (CA? Palo Alto? Symantec? Trend Micro?) will buy LogRhythm.
  5. Each of the technology elements described above could be delivered on-premises or via SaaS options. SOAPA must be flexible to accommodate these options.
  6. SOAPA must be built for immense scale – especially as organizations increase their use of cloud computing and IoT. It’s likely cloud analytics or storage will become part of the architecture.
  7. A few vendors may be able to deliver their own proprietary SOAPA solutions but enterprise customers will likely eschew single vendor solutions while anchoring their SOAPAs with lead vendors and ecosystem partners. Small enterprises and SMBs could buy from a single product or SaaS vendor however.

Cyber Security Frameworks


Cyber Security Frameworks



Cyber Threats

Cyber Threats

List of Cyber Threats

  • Malicious software
  • Unauthrized access
  • Denial of Service
  • Data Leak
  • Unauthrozed use of services
  • Government and competitor cyber espionage
    • 3rd Party attack
  • https://www.cpni.gov.uk/advice/cyber/Cyber-Attack-Types/
  • https://www.getcybersafe.gc.ca/cnt/rsks/index-en.aspx
  • Physical Security
    • Theft
  • Human Error
      • misdelivery of sensitive information to the wrong person by email or fax;
      • mistakenly making information publicly available on a web server or website;
      • losing or inadequately disposing of data, including paper records;
      • losing an unencrypted laptop, cellphone or storage device such as a USB key.
  • Insider Threat
    • Misuse of privileges by rogue employee or other insiders,
    • Payment card skimmers, a skimming device is implanted in a device that reads magnetic stripe data from a payment card. Examples include ATMs, gas pumps, and POS (Point of Sale) terminals.
  • Cyber Risk and Business Impact Analysis

RTLO (right to left override) technique for file extension spoofing U+202e

RTLO (right to left override) technique for file extension spoofing

Step-by-Step Guide

U+202E 2017-03-27 10-34-50

  1. Open Windows Character Map Tool (Start, Run, Charmap)
  2. Go to Unicode 202E: Right-To-Left Override
  3. Click Select and then Copy
  4. Edit a file name and just before the . Paste here. (Example, notepad.exe notepad[202E].exe
  5. Then type in the file extension your require.
    1. doc=cod
    2. pdf=fdp
  6. User Resource Hacker to change the ICON (http://www.angusj.com/resourcehacker/)

Self Extracting and Executing archive SFX



  1. Email encrypted self extracting SFX file that is a .SCR VbScript with file name that looks like a PDF using 202E which then executes DLL to download payload and executes in users admin area.

Essentially, the file’s actual name can be something like “Awesome Song uploaded by [U+202e]3pm.SCR”. The special character forces Windows to display the end of the file’s name in reverse, so the file’s name will appear as “Awesome Song uploaded by RCS.mp3”. However, it’s not an MP3 file – it’s an SCR file and it will be executed if you double-click it. (See below for more types of dangerous file extensions.)

Method 1: Universal

This method works regardless of any of your language settings, but is the most cumbersome to type.

  1. Press and hold down the Alt key.
  2. Press the + (plus) key on the numeric keypad.
  3. Type the hexidecimal unicode value.
  4. Release the Alt key.

Alas, this appears to require a registry setting. It was already set on my computer, but some readers report that this method didn’t work for them, and this is probably why. If you don’t know what the registry is, please don’t try this. Under HKEY_Current_User/Control Panel/Input Method, set EnableHexNumpad to “1”. If you have to add it, set the type to be REG_SZ.

Method 2: Input-language Specific

This method depends on the specific input language you are using.

  1. Press and hold down the Alt key.
  2. Type 0 (zero) and the decimal unicode value on the numeric keypad.
  3. Release the Alt key.

You can see which input language you are using (and which are installed) by:

  1. Start Menu
  2. Settings
  3. Control Panel
  4. Regional and Language Options
  5. Languages tab
  6. Detail button

The entries in the Unicode character information section are using the Windows Latin 1 input language.

Method 3: Code-page Specific

This method depends on the specific code page you have installed.

  1. Press and hold down the Alt key.
  2. Type the decimal codepage value on the numeric keypad. Do not type any leading zeros.
  3. Release the Alt key.

You can see which code page you have by typing chcp at a command prompt. Check the grid for your code page from the list of known code pages to see what characters you can enter this way.

The entries in the Unicode character information section are using code page 437.

Method 4: Application-specific

Applications can support their own methods. These are not standardized.

Several Microsoft applications, including WordPad and Microsoft Word:
press Alt-X after typing some hex digits. You see the digits as you type them, and they’re replaced by the Unicode equivalent. Pressing Alt-X again converts it back to numbers.

Method 5: Unicode IME

Microsoft has a Unicode Input Method ?Editor? that works the same way my UnicodeInput pop-up does, but with LeftAlt Shift as the trigger key.

Michael Kaplan, a Microsoft i18n guru, has the details on how the Unicode IME works. Some notes to fill in some details that he assumes:

  • Go into Control Panel -> Regional Settings, on the languages tab, enable support for East Asian languages. This takes 230 MB of disk space and a restart.
  • Go back into Control Panel -> Regional Settings, on the languages tab, press the Details button.
  • Add Chinese (Taiwan) (Others would probably work too) and choose Chinese (Traditional) - Unicode.
  • You will now have an extra do-hickey in the taskbar showing which language you’re in.
  • Press LeftAlt Shift to switch into the IME (taskbar shows CH).
  • Type the hex digits of the Unicode character. As soon as you type the last one, it is sent to the application.
  • Press LeftAlt Shift to switch out of the IME (taskbar shows your original language code).


  • Fonts – you must have a font that contains the character. It seems obvious, but Windows can’t display characters it doesn’t know about. Often, you will need to select the font yourself, since only a few applications are smart enough to switch fonts automatically.
  • WordPad – works, but you have to have it set to a font that contains the character. Method 4 ([hex][AltX]) seems to switch to an appropriate font automatically.
  • Notepad – generally doesn’t work since its font doesn’t support many characters.
  • Internet Explorer – in the URL bar, the universal method doesn’t work if it has A-F, since it opens the menu (i.e. Alt-F opens the File menu).
  • Mozilla Firebird – works correctly (if you have a font that supports it). Note that if you type it on a page that is is using a charset that doesn’t support it, it will not be transmitted to the website correctly.


  • The Alt+NumPad entry in Microsoft’s Global Windows Glossary
  • Windows XP docs that inexcusably don’t mention the universal variation.
  • Discussion on GeorgeHernandez.com (search for “2005-04-24”) – discussion of the various problems with someone who did some real work to figure out what works and doesn’t. He also has a Unicode shortcuts page that summarizes his findings (quite similar to this page, but with more detail).
  • Wikipedia article Unicode_input with some Mac and Linux tips.

Influence Approaches for Different Personality Styles

Influence Approaches for Different Personality Styles

Pragmatic/Driver: Example – Jack Welch former CEO of GE. The pragmatic wants quick results, gets to the point, task-oriented, more controlling of others, acts first then thinks, assertive, risk taker. The best principles of influence when dealing with this personality type would be:

  • Authority – They may not care what the crowd says but prove your point with the opinion or experience of an expert or someone they respect or admire, and they’ll listen.
  • Scarcity – Drivers are successful because they win! Show them what they might lose if they don’t do what you’re asking and you’ll grab their attention.
  • Consistency – Their self-confidence makes them believe they’re right so they might seem like they stubbornly hold to an opinion. If you can tie your request to what they’ve said or done in the past your odds of success will go up.

Influencer/Expressive: Example – Oprah Winfrey. The influencer is focused on social groups and events, more in tune with people than tasks, imaginative, usually sway others, and likes innovation. The best way to engage these individuals would be using the following principles of influence:

  • Sarcity – Influencers don’t want to lose out on opportunities to move people to action. Talk about how they might lose an opportunity and you’ll have a good chance of hearing “Yes!”
  • Reciprocity – They understand how engaging with favors helps because they frequently use that tactic when they persuade. Do something for them and they’ll try to return the favor to build their network.
  • Liking – Expressive people are talkers and quite often like to talk about themselves. Pay a genuine compliment or ask about something they’re into and they appreciate you for taking interest.

Facilitator/Amiable: Example – Sandra Bullock. Facilitators like stable relationships, focus on feelings, less assertive, more people-focused, slow to change, and wants product support. The psychology of persuasion to utilize for this group would be:

  • Consensus – Because they’re so likable and want everyone to get along showing them what many others are already doing will help your case.
  • Liking – They naturally like others and want to be liked so use liking to come to know them and like them and you’ll increase your chance to influence.
  • Reciprocity – Giving small gifts, time, effort, etc. conveys thoughtfulness to the facilitator and will likely be returned in kind.

Thinker/Analytical: Example – Albert Einstein. Thinkers are task-oriented, slower to act, exert self-control, less assertive, data-oriented, prudent, systematic, logical, look to track records/trends. When dealing with this type of person you should look to use the following principles of influence:

Learning Python for Networking

Learning Python for Networking

Python the Hardway – https://learnpythonthehardway.org/book/?__s=ng1wguqfgy4mttisodvu

Python2 vs Python3 (relevant differences for beginners):

Darren O’Connor has a recent blog post about passing arguments into a Python script (Darren is a dual-CCIE, JNCIE who has some blog posts about Python):

For more complicated argument parsing check out Argparse (requires Python 2.7) or getopt:

Getting Python Installed

You will need a system that has Python2.7 on it.

If you are running a recent version of MacOS X, then you will already have Python 2.7 (launch Terminal and type ‘python’ at the prompt).

Just type ‘python’ from the shell and verify it has Python2.7.

If you are running on Windows, then you should be able to download and install it from here:


Either the ‘Windows x86-64 MSI Installer’ or the ‘Windows x86 MSI Installer’ is probably the right choice.

You might also want to update your Windows system Path so that your computer knows how to find the Python interpreter.  You should be able to find this process online (for your version of Windows).


You can also use an online Python Interpreter (at least for some of the course). You can find one online at http://repl.it/languages/Python.


Network Config Templating using Ansible

The general problem is this: you want a systematic way of creating network device configurations based on templates and variables.

As background, Ansible is an open-source automation application that can be used to automate many tasks in your environment (predominantly compute and cloud tasks). Ansible can also generate files based on Jinja2 templates and variables. Jinja2 is a widely-used Python templating system, see http://jinja.pocoo.org/ for more information about Jinja2.
Thus, Ansible has all the components for network configuration templating built into it.  This is a very good initial use case for Ansible for network engineers.

Part1 – https://pynet.twb-tech.com/blog/ansible/ansible-cfg-template.html

Part2 – https://pynet.twb-tech.com/blog/ansible/ansible-cfg-template-p2.html

Part3 – https://pynet.twb-tech.com/blog/ansible/ansible-cfg-template-p3.html

Week 1

  1. Introduction and Some Questions
    video https://vimeo.com/119478712
    Length is 11 minutes
    The ‘Some Questions’ section continues into the first 1:12 of the next video
  2. Characteristics of Python
    video https://vimeo.com/119480935
    Length is 7 minutes
  3. Interpreter Shell, Variables, and Assignment
    video http://youtu.be/6ja4KlejT-g
    Length is 8 minutes
  4. Strings
    video http://youtu.be/ItIE8hItji8
    Length is 19 minutes

Week 2

  1. Introduction (Week2)
    video http://youtu.be/uqGZXPfX00E
    Length is 2 minutes
  2. Print and raw_input
    video http://youtu.be/pEXUxySxygg
    Length is 14 minutes
  3. Numbers
    video http://youtu.be/n5ZO8rRcWbA
    Length is 12 minutes
  4. Lists and Tuples
    video http://youtu.be/nUOMXXhQgZQ
    Length is 14 minutes
  5. Booleans
    video http://youtu.be/gCpRBt7pw-0
    Length is 5 minutes

Week 3

  1. Introduction Week  https://vimeo.com/120754390
  2. If Conditionals  http://youtu.be/5lHWv9hkSn8
  3. For Loops http://youtu.be/VR0ggQuClOM
  4. Passing Arguments into a Script http://youtu.be/mUt0uJmD9y4

Week 4

  1. Introduction Week 4  http://youtu.be/UJmDynoQxps
  2. While Loops http://youtu.be/xnZzrnAQdG
  3. Dictionaries http://youtu.be/iGVJmUXcLtI
  4. Exceptions http://youtu.be/fCkjmtIq7wU


In this article, I briefly introduce Python and SNMP using the pysnmp library.

I assume that you already have some knowledge on SNMP including MIBs and OIDs.  If not, you should be able to find this information fairly easily on the Internet.


In order to get started, you need to install the pysnmp library.  For context, I am testing on an AWS AMI server (RedHat based i.e. yum instead of apt).

For installation just use ‘pip’:
# As root or sudo (or in a virtual environment)
$ pip install pysnmp

I also installed net-snmp to simplify testing and to add an easy way to perform an SNMP walk.  The installation method for net-snmp will vary depending on your system.

# As root or sudo
$ yum install net-snmp
$ yum install net-snmp-utils


To keep things simple I am only going to use SNMPv1/2c (i.e. this article does not cover SNMPv3).  This is obviously not secure.


Now that I have the pysnmp library installed, the next step is to verify that I can communicate with my test router using SNMP.  First, let’s test this directly from the Linux command line:

$ snmpget -v 2c -c <COMMUNITY> <IP_ADDR> .
SNMPv2-MIB::sysDescr.0 = STRING: Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version 15.0(1)M4, RELEASE SOFTWARE (fc1)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2010 by Cisco Systems, Inc.
Compiled Fri 29-Oct-10 00:02 by prod_rel_team
The OID . is the MIB-2 sysDecr object.  During testing I had multiple problems getting SNMP to work on the router including that I had Cisco’s Control Plane Policing enabled (ooops) and that I needed to allow access through both an edge ACL and through a separate SNMP ACL.

At this point, I am able to communicate using SNMP from my AWS server to my test router.


Now let’s try the same thing except using the pysnmp library.  In order to simplify this I have created a couple of SNMP helper functions see:


First we need to do some initialization:

>>> from snmp_helper import snmp_get_oid,snmp_extract
>>> SNMP_PORT = 161
>>> a_device = (‘’, COMMUNITY_STRING, SNMP_PORT)

This code loads my two functions (snmp_get_oid and snmp_extract); it also creates a tuple named ‘a_device’ consisting of an IP, community string, and port 161.

I then call my snmp_get_oid function using the OID of MIB-2 sysDescr:
>>> snmp_data = snmp_get_oid(a_device, oid=’.′, display_errors=True)
>>> snmp_data
[(MibVariable(ObjectName(, DisplayString(hexValue=’436973636f20494f5320536f6674776172652c204338383020536f6674776172652
I can see that I received SNMP data back albeit in an ugly format.  I can now use the snmp_extract function to display the output in a more friendly way.

>>> output = snmp_extract(snmp_data)
>>> print output
Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version 15.0(1)M4, RELEASE SOFTWARE (fc1)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2010 by Cisco Systems, Inc.
Compiled Fri 29-Oct-10 00:02 by prod_rel_team


Now, let’s repeat this process but using a different OID.  Using snmpwalk on the ‘interfaces’ MIB and the Cisco SNMP Object Navigator, I was able to determine that the OID = . corresponded to the output octets on FastEthernet4.


Here I query that OID a couple of times in fairly quick succession (less than a minute between queries):
>>> snmp_data = snmp_get_oid(a_device, oid=’.′, display_errors=True)
>>> output = snmp_extract(snmp_data)
>>> print output

>>> snmp_data = snmp_get_oid(a_device, oid=’.′, display_errors=True)
>>> output = snmp_extract(snmp_data)
>>> print output

You can see that the count incremented.


Week 5


I. Class Review (weeks 1 – 4)
video https://vimeo.com/121951502
Length is 16 minutes




In these two exercises, I am going to use the following diagram and CDP data:
CDP data

Disclaimer: the CDP data is from a test switch and a test router. I have manually modified this data to be consistent with the above diagram.
Reference code for these exercises is posted at:


1. Parse the CDP data (see link above) to obtain the following information: hostname, ip, model, vendor, and device_type (device_type will be either ‘router’, ‘switch’, or ‘unknown’).

From this data create a dictionary of all the network devices.

The network_devices dictionary should have the following format:

network_devices = {
‘SW1’: { ‘ip’: ‘’, ‘model’: ‘WS-C2950-24’, ‘vendor’: ‘cisco’, ‘device_type’: ‘switch’ },
‘R1’: { ‘ip’: ‘’, ‘model’: ‘881’, ‘vendor’: ‘Cisco’, ‘device_type’: ‘router’ },

‘R5’: { ‘ip’: ‘’, ‘model’: ‘881’, ‘vendor’: ‘Cisco’, ‘device_type’: ‘router’ },

Note, this data structure is a dictionary that contains additional dictionaries.  The key to the outer dictionary is a hostname and the data corresponding to this key is another dictionary.  For example, for ‘R1’:

>>> network_devices[‘R1’]
{‘ip’: ‘’, ‘model’: ‘881’, ‘vendor’: ‘Cisco’, ‘device_type’: ‘router’}

You can access a given attribute in the inner dictionary as follows:
>>> a_dict[‘R1’][‘ip’]

If this is confusing, you might want to experiment with it in the Python shell:

##### Python Shell – experimenting with dictionary of dictionaries #####

# Initialize network_devices to be a blank dictionary
>>> network_devices = {}

# Assign the key ‘R1’ to network_devices using a value of a blank dictionary (in other words, I am adding a key:value pair to network_devices where the key is ‘R1’ and the value is {} )
>>> network_devices[‘R1’] = {}

# Look at network_devices at this point
>>> network_devices
{‘R1’: {}}

# Add the ‘ip’ and ‘vendor’ fields to the inner dictionary
>>> network_devices[‘R1’][‘ip’] = ‘’
>>> network_devices[‘R1’][‘vendor’] = ‘Cisco’
>>> network_devices
{‘R1’: {‘ip’: ‘’, ‘vendor’: ‘Cisco’}}

##### Python Shell – experimenting end #####

For the output to this exercise, print network_devices to standard output.  Your output should look similar to the following (six network devices with their associated attributes).

{‘R1’: {‘device_type’: ‘Router’,
‘ip’: ‘’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘R2’: {‘device_type’: ‘Router’,
‘ip’: ‘’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘R3’: {‘device_type’: ‘Router’,
‘ip’: ‘’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘R4’: {‘device_type’: ‘Router’,
‘ip’: ‘’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘R5’: {‘device_type’: ‘Router’,
‘ip’: ‘’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘SW1’: {‘device_type’: ‘Switch’,
‘ip’: ‘’,
‘model’: ‘WS-C2950-24’,
‘vendor’: ‘cisco’}}

2. Create a second program that expands upon the program from exercise 1.

This program will keep track of which network devices are physically adjacent to each other (physically connected to each other).

You will accomplish this by adding a new field (adjacent_devices) to your network_devices inner dictionary.  adjacent_devices will be a list of hostnames that a given network device is physically connected to.  

For example, the dictionary entries for ‘R1’ and ‘SW1’ should look as follows:

‘R1’: {‘IP’: ‘’,
‘adjacent_devices’: [‘SW1’],
‘device_type’: ‘Router’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},

‘SW1’: {‘IP’: ‘’,
‘adjacent_devices’: [‘R1’, ‘R2’, ‘R3’, ‘R4’, ‘R5’],
‘device_type’: ‘Switch’,
‘model’: ‘WS-C2950-24’,
‘vendor’: ‘cisco’},


For the output to this exercise, print network_devices to standard output.  Your output should look similar to the following (six network devices with their associated attributes including ‘adjacent_devices’).

{‘R1’: {‘IP’: ‘’,
‘adjacent_devices’: [‘SW1’],
‘device_type’: ‘Router’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘R2’: {‘IP’: ‘’,
‘adjacent_devices’: [‘SW1’],
‘device_type’: ‘Router’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘R3’: {‘IP’: ‘’,
‘adjacent_devices’: [‘SW1’],
‘device_type’: ‘Router’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘R4’: {‘IP’: ‘’,
‘adjacent_devices’: [‘SW1’],
‘device_type’: ‘Router’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘R5’: {‘IP’: ‘’,
‘adjacent_devices’: [‘SW1’],
‘device_type’: ‘Router’,
‘model’: ‘881’,
‘vendor’: ‘Cisco’},
‘SW1’: {‘IP’: ‘’,
‘adjacent_devices’: [‘R1’, ‘R2’, ‘R3’, ‘R4’, ‘R5’],
‘device_type’: ‘Switch’,
‘model’: ‘WS-C2950-24’,
‘vendor’: ‘cisco’}}




Video Archive

Introduction and Some Questions
What is the Nature of Python
Interpreter Shell, Variables, and Assignment

Print and raw_input
Lists and Tuples

If Conditionals
For Loops
Passing Arguments into a Script

While Loops




Kirk Byers
Twitter: @kirkbyers