Showing posts with label Cisco. Show all posts
Showing posts with label Cisco. Show all posts

Friday, July 27, 2018

Learning Python 3

Updated September 10th, 2022

Here are some of the resources I used to start learning python. With my newly learned  Python skills and some Google-Fu I have been able to automate several network device tasks. You can find most of my python scripts at Hubbard on Networking GitHub Repo.

You do NOT need to know anything about python to use the scripts. This is just like you don't have to know how to program to run "show interface g1/0/1". You simply download the script and execute it.

I found this tweet that has a curated list of python resources:


Why You Should Learn Python

A lot of the tasks that network engineers perform are repetitive, mind-numbing, and error-prone. With a little python skill, you can automate these tasks and spend the time you save on more productive tasks, like learning more python.

As networking moves away from the CLI and into software-defined networking (SDN) you will need to have some dev skills. Cisco has a three-part video on how the network engineer's job is changing. You will need to register with Cisco Devnet to watch it but you should have a Devnet account if you going down this path:
Lesson 1: The Network Engineer of Old

If you have never used Python at all, this blog is the place to get started!

First, to install python, head over to the Python download page - Download Python
Follow the instructions to install python on your OS of choice.

Tools

There isn't much needed to use Python other than python itself but like most things, life is easier with some tools.

Integrated Development Environment (IDE)

IDEs are tools that allow you to write and debug code. Once you start writing scripts that are more than a few lines long you will want to use an IDE.

Thonny - Python IDE for beginners. A free Integrated Development Environment. This tool is great for learning. It lets you step through a script and see exactly what is happening.

MU - a simple Python editor for beginner programmers. This one is really nice. It's cross-platform and has support for Linux, Mac, Windows, and Raspian. What separates it from the other tools listed here is the support for small devices like Adafruit and Micro:bit. Here is a screenshot of MU starting up:



Microsoft Visual Studio Code - A free open source IDE from Microsoft. VSCode has turned into an amazing development environment and can be used for any size project. It has an integrated debugger that looks just like the Powershell ISE tool. It supports almost every programming language, not just python. The open-source version of PowerShell is fully supported which is great. I can use one tool and create Python and PowerShell scripts. 

There is a Visual Studio Marketplace with thousands of plugins, similar to the Chrome store or Firefox store. Extensions for the Visual Studio family of products

I have more detail on my macOS blog. Once you have VScode installed it works the same on Windows, Mac, and Linux so the blog is useful regardless of what OS you use. My VSCode install blog

Code Editor

You can definitely use VSCode as your editor. It has about every feature that you could want. But I have been using Sublime text since before VSCode came out and old habits die hard! If you are on Ubuntu 22.04 you can install Gnome Text Editor (I know, really, really stupid name) and it works great for quick editing.

Sublime text - Sublime is a text editor that is optimized for programming. It has a huge community around it and thousands of plugins. It's $75.00 but the license lets you run it on as many machines as you own. I bought it and installed it on my Linux, Windows, and Mac laptops. It has a tabbed interface like notepad++ which I like. You can also split the screen and open two files side by side. This is useful because you can have your script on one side and the data file on the other. 

Realpython.com sells a great tutorial that walks you through installing Sublime text optimized for Python. It includes video and text for Mac, Linux, and Windows. This tutorial is well worth the cost and has improved my productivity in Sublime.

In the next section, I discuss revision control with Git. Sublime text has several plugins that integrate Git into your workflow.  One I really like is Git Gutter. It puts a + sign next to lines that have changed, then you can revert easily if the change didn’t work.
Your Shortcut to a Professional Python Development Setup

Revision Control

Git - A revision control system. It's useful once you start writing scripts large enough to have bugs or future enhancements. Even if you don't program in python it's worth installing git because of github.com and gitlab.com.

Both of these sites have thousands of python tools. If you have git installed on your computer all you have to do to use them is "git clone <repository>". For example, to install the ARP sorting tool I wrote, you simply go to ARP-Sort and click the "Code" button. It will display the URL for the project. Click the copy button, type “git clone” and paste the URL you copied into the terminal, then press enter:

git clone https://github.com/rikosintie/ARP-Sort.git

This downloads the project and unzips it into the folder ARP-Sort.




Someone has created an online game for learning Git - An open source game about learning Git!
Cisco DevNet GitHub Repo - Great resources on setting up your laptop with Python, Git, Postman, etc.
Git and GitHub for Beginners - Crash Course - A really good video on git.
 



Videos from Udemy.com 

Udemy has inexpensive video training for Python, Linux, and a lot of other applications. These are on sale all the time for $9.99

  • Python Network Programming - Part 1: Build 7 Python Apps
  • Complete Python Bootcamp: Go from zero to hero in Python 3
  • 100 Days of Code - The Complete Python Pro Bootcamp for 2021

Videos on Youtube

I find that I learn better when using books and websites but sometimes it's nice to watch a video.

Real python did a blog on the best Youtube channels for python
The Ultimate List of Python YouTube Channels

Subscribe to HackerSploit on Youtube and there is a complete series on Python. He uses 2.7 but it is still a good tutorial. They are really basic but I find Alexis entertaining.
Python For Ethical Hacking - #1 - Introduction & Python Modules

Telusko Python for Beginners
Python Tutorial - Python for Beginners [Full Course] - Mosh 
Learn Python - Full Course for Beginners [Tutorial] Free Code Camp
Writing Pythonic Code - A Tweet thread by @Bascodes. He is worth following.

Corey Shafer Videos

I recommend that you subscribe to this channel. Here are four of his videos that I found very useful

Requests Tutorial - The requests library is used to pull data down from webservers
JSON Tutorial - Java Script Object Notation is a common data format used by APIs
Sorting Tutorial - Sorting routines for lists and dictionaries
List Comprehensions - Working with list comprehensions

e-books from Amazon  

I love the Kindle app on my laptop, phone and iPad. If I get stuck in a long line I just open it up and do some studying! These were all under $5. You can go to Amazon, set filter to Kindle store and enter "python programming free book" and find a lot of free books.

  • Learn Python in One Day and Learn It Well Python for Beginners with Hands-on Project The only book you need to start coding in Python immediately By Jamie Chan
  • Python Tips and Tricks: Learn the Best Tips and Tricks to Get The Most out of Python NOW! Jones, Daniel
  • The Fundamentals Of Python Programming: A Complete Beginners Guide To Python Mastery.
  • Python Programming Tips and Tricks: The Ultimate Cheat Sheet for Python Programming. 20+ Tips and Tricks to Make Your Life Easier and More Efficient
  • Automate the Boring Stuff with Python: Practical Programming for Total Beginners


Websites

There are so many python websites it would be impossible to list them all, here are a few I have found very useful:

Getting Started

General Tips

Jinja Templates

Network Engineering

Debugging

Web Development


Style guides

Python is a structured language that uses white space as part of the structure. But you can still create ugly code. The official Python style guide is part of the Python Enhancement Proposals (PEPs) which are documents that provide guidance and spell out best practices for how Python code should be organized, packaged, released, deprecated, and so on. PEP8 is a popular standard for styling Python code and is extensively used in the developer community. 

Python Virtual Environments

As you start learning and creating more python tools you will want to start using virtual environments. These two blogs will teach you what you need to know. There are a lot more blogs available on the Internet.

Podcasts

You probably won't learn much coding from a podcast but these are very interesting to listen to. I find a lot of good links in the show notes. For example, I learned about Thonny, MU, and Visual Studio Code from podcasts.
Talk Python To Me - A good podcast that covers a lot of topics. There will be one called "Teaching Python to network engineers" in August, 2018!
Podcast.__init__ - A podcast about Python and the people who make it great. Hosted by Tobias Macey.
Python Bytes - Python Bytes podcast delivers headlines directly to your earbuds. If you want to stay up on the Python developer news but don’t have time to scour Reddit, Twitter, and other news sources, just subscribe and you’ll get the best picks delivered weekly.

Keywords In Python

There are 33 keywords that should never be used as a variable, function name, class, object, or as any other identifiers in your programs.

 false
 True
 finally
 class
 for
 continue
 none
 return
 lambda
 try
 is
 def
 from
 nonlocal
 while
 and
 not
 global
 del
 with
 as
 elif
 if
 or
yield
 break
 import
 except
 pass
 assert
 else
 raise
 in

Libraries

Pint - Pint is a Python package to define, operate and manipulate physical quantities

Saturday, May 7, 2016

ESXi vSwitch Configuration for Cisco Cross Stack Etherchannel

There are a lot of examples of how to set up an ESXi vSwitch to work with Cisco Etherchannel available on the Internet. But I still get asked quite often how to do it so I decided to document how I do it.

References

Best Practices for Virtual Networking
Host requirements for link aggregation for ESXi and ESX (1001938)
Sample configuration of EtherChannel / Link Aggregation Control Protocol (LACP) with ESXi/ESX and Cisco/HP switches (1004048)
VMware KB: Understanding IP Hash load balancing

The Hardware

In this example there are two Dell servers running ESXi.

There are two Cisco 2960x switches with stacking modules but this example will work with most Cisco Catalyst switches that are configured as a stack. 

Server Connections

Each server has a four built in Gb interfaces and a four port add in Gb adapter. We will use one port from each adapter for VMware management and one port from each adapter for Guest traffic. You can easily scale the example to use all eight NICs.

Two ports for VM management

  • Dell Built in port 1 (vmnic0)
  • Dell Add on Port far Left (vmnic7)

vSwitch0 used for Management
vmk0, vlan 54


Click on Properties… and select vSwitch, Edit.
vSwitch0



Click the NIC Teaming tab



Set Load Balancing to "Route based on IP hash"
Set Network Failover Detection to "Link status only"
Set Notify Switches to "Yes"
Set Fallback to "Yes"

Make sure vnmic0 and vmnic7 are the Active Adapters. You may have to select and then use the "Move Up" button if one of them is in standby.

Click Ok and select the Management Network, Edit.


Select the NIC Teaming tab


Set Load Balancing to "Route based on IP hash"
Set Network Failover Detection to "Link status only"
Set Notify Switches to "Yes"
Set Fallback to "Yes"

Make sure vnmic0 and vmnic7 are the Active Adapters. You may have to select and then use the "Move Up" button if one of them is in standby. Click Ok.

Two Ports for Guest Traffic

  • Dell Built in port 4 (vmnic3)
  • Dell Add on port Far right (vmnic4)
vSwitch1 used for Guest traffic
vmk1, vlan 50



Click on Properties… and select vSwitch, Edit.

Select the NIC Teaming tab


Set Load Balancing to "Route based on IP hash"
Set Network Failover Detection to "Link status only"
Set Notify Switches to "Yes"
Set Fallback to "Yes"

Make sure vnmic3 and vmnic4 are the Active Adapters. You may have to select and then use the "Move Up" button if one of them is in standby.

Click Ok and select the Management Network, Edit.
Select the NIC Teaming tab


Set Load Balancing to "Route based on IP hash"
Set Network Failover Detection to "Link status only"
Set Notify Switches to "Yes"
Set Fallback to "Yes"

Make sure vnmic3 and vmnic4 are the Active Adapters. You may have to select and then use the "Move Up" button if one of them is in standby.

Here's a look at the physical network adapters


That's it for the server. 

Cisco Switch Configuration

From VMware KB 1001938
The switch must be set to perform 802.3ad link aggregation in static mode ON and the virtual switch must have its load balancing method set to Route based on IP hash.
Ensure that the participating NICs are connected to the ports configured on the same physical switch or stacked switch.

If this is a new deployment you can configure the switch to use src-dst-ip for Etherchannel and connect the ESXi servers.

But if you are adding ESXi servers to an existing switch that already has Etherchannels defined you should check the current port-channel load balancing mode before making any changes (and make a backup of the current switch configuration).

Use Show Etherchannel load-balance to see the current setting. For a 2960x the default is src-mac.

TEST#sh etherchannel load-balance
EtherChannel Load-Balancing Configuration:
        src-mac

EtherChannel Load-Balancing Addresses Used Per-Protocol:
Non-IP: Source MAC address
  IPv4: Source MAC address
  IPv6: Source MAC address

You can see that the default uses the Source MAC address instead the IP address. I haven't had any problems connecting a 2960x to a 4507R+E using Etherchannel after making the change but you should be aware of what is in use before making a change.

In global configuration mode:
port-channel load-balance src-dst-ip

This sets the Etherchannel load balancing to match the ESXi vSwitch mode.

In the interface configuration we will add:
channel-group X mode on

On is used instead of Active because VMware doesn’t support negotiation. 

Switch configurations

port-channel load-balance src-dst-ip

interface Port-channel1
 description < Uplink to Core >
 switchport mode trunk
no shut
!
interface Port-channel2
 description < ESX02 management >
 switchport trunk allowed vlan 54
 switchport mode trunk
no shut
!
interface Port-channel3
 description < ESX02 VM >
 switchport mode trunk
no shut
!
interface Port-channel4
 description < ESX01 management>
 switchport trunk allowed vlan 54
 switchport mode trunk
 no shut
!
interface Port-channel5
 description < ESX01 VM >
switchport mode trunk
no shut
!
interface GigabitEthernet1/0/45
 description < ESX01-MG1 >
 switchport trunk allowed vlan 54
 switchport mode trunk
 channel-group 4 mode on
!
interface GigabitEthernet1/0/46
 description < ESX01-VM1 >
 switchport trunk allowed vlan 50
 switchport mode trunk
 channel-group 5 mode on
!
interface GigabitEthernet1/0/47
 description < ESX02-MG1 >
 switchport trunk allowed vlan 54
 switchport mode trunk
 channel-group 2 mode on
!
interface GigabitEthernet1/0/48
 description < ESX02-VM1 >
 switchport trunk allowed vlan 50
 switchport mode trunk
 channel-group 3 mode on
!

interface GigabitEthernet2/0/45
 description <  ESX01-MG2 >
 switchport trunk allowed vlan 54
 switchport mode trunk
 channel-group 4 mode on
!
interface GigabitEthernet2/0/46
 description < ESX01-VM2 >
 switchport trunk allowed vlan 50
 switchport mode trunk
 channel-group 5 mode on
!
interface GigabitEthernet2/0/47
 description <  ESX02-MG2 >
 switchport trunk allowed vlan 54
 switchport mode trunk
 channel-group 2 mode on
!
interface GigabitEthernet2/0/48
 description < ESX02-VM2 >
 switchport trunk allowed vlan 50
 switchport mode trunk
 channel-group 3 mode on
!

Show commands

  • Show Etherchannel Sum – Shows status of the port channel and each port
  • Show Etherchannel load-balance – Shows load balance mode. Should be src-dst-ip.
  • Show Etherchannel detail – Shows detailed information about the port channel.

Show Etherchannel Sum
TEST#Show Etherchannel Sum
Flags:  D – down P - bundled in port-channel
I - stand-alone s - suspended
H - Hot-standby (LACP only)
R - Layer3      S - Layer2
U - in use      f - failed to allocate aggregator

M - not in use, minimum links not met
u - unsuitable for bundling
w - waiting to be aggregated
d - default port

Number of channel-groups in use: 5
Number of aggregators:           5

| Group | Port-channel | Protocol | Ports                   |
|:-----: |:------------: |:--------: |------------------------- |
|   1   |    Po1(SU)   |   LACP   | Te1/0/1(P)  Te2/0/1(P)   |
|   2   |    Po2(SU)   |     -     | Gi1/0/47(P) Gi2/0/47(P) |
|   3   |    Po3(SU)   |     -     | Gi1/0/48(P) Gi2/0/48(P) |
|   4   |    Po4(SU)   |     -     | Gi1/0/45(P) Gi2/0/45(P) |
|   5   |    Po5(SU)   |     -     | Gi1/0/46(P) Gi2/0/46(P) |

Show Etherchannel load-balance
TEST#Show Etherchannel load-balance
EtherChannel Load-Balancing Configuration:
        src-dst-ip

EtherChannel Load-Balancing Addresses Used Per-Protocol:
Non-IP: Source XOR Destination MAC address
  IPv4: Source XOR Destination IP address
  IPv6: Source XOR Destination IP address

Test the load balancing 
test etherchannel load-balance interface port-channel 3 <source IP> <dest IP>

TEST#test etherchannel load-balance interface port-channel 3 ip 10.26.50.100 10.26.50.101
Would select Gi1/0/48 of Po3

TEST#
TEST#test etherchannel load-balance interface port-channel 3 ip 10.26.50.100 10.26.54.102
Would select Gi2/0/47 of Po3

TEST#

Trouble Shooting

The reference link "IP Hash Load Balancing" lists the following under "Disadvantages" of using Port-channels:

Beacon probing is not supported with IP Hash. Only link status can be used as a failure detection method. If a link fails without the link state going down, there is no way to avoid network communication issues on the vSwitch.

This is a serious problem if one of the links is UP but the protocol is down. Symptoms are some servers are reachable and some aren't. The first time you run into this it can be a challenge to figure out, especially if you are remote and depending on someone on site to give you information. Keep this in the back of your mind.

Tuesday, April 26, 2016

Calculate the Fingerprint from an RSA Public Key

Updated July 5th, 2017.
SSH is a great protocol that encrypts traffic between the client and the server (among many other things that it does). But it doesn't provide authentication. That can leave you open to a Man in the Middle (MiTM) attack. You have probably started an SSH session to a switch, router or server and seen this dialog (or a similar one depending you the OS you are using):


The message reinforces the fact that SSH doesn't provide authentication. So what to do? 

In a previous blog Discovering SSH host keys with NMAP I showed you how to use NMAP to pull the fingerprint or full SSH key from a Cisco device. The problem here is that you still can't be sure that the device you scanned is actually the device you want to connect to.  

With newer Cisco IOS versions you can easily display the full RSA key of the device. If you are connected with a console cable there is no doubt that you are connected to the correct device. So you can record the key right after you generate it during the initial setup with a console cable.

Once you have the full key it's easy to get the fingerprint using OpenSSH on Linux/MAC. For windows users Didier Stevens over at the SANS InfoSec forums wrote a Python script you can use. His post can be found at SSH Fingerprints Are Important.

Here is the output on the switch
3750x#sh ip ssh
SSH Enabled - version 2.0
Authentication methods:publickey,keyboard-interactive,password
Encryption Algorithms:aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
MAC Algorithms:hmac-sha1,hmac-sha1-96
Authentication timeout: 120 secs; Authentication retries: 3
Minimum expected Diffie Hellman key size : 1024 bits
IOS Keys in SECSH format(ssh-rsa, base64 encoded):
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDQbH8FnvSpDpEsL3OzzWal1DCFBQmiImg4WWhSwlCu9mdHb53YigPEXJOlsVdX9KTKIACvwyHu5+yRQXa6+7Ahp7f98c1ac8wRW4Q8EP35kI00l+40LoC5G8eMiZ5Pz8o8UyAD/zmY1vWJzxs8k4mtdvgI4Pf5C3mmJ8r2nu0Zjw==

Some things to note here 
SSH Enabled - Version 2.0. It is critical that you don't allow your devices to use ANY version of SSH except 2.0. You do this by issuing "IP SSH Version 2" from global config mode. If you see version 1.99 then your device will accept SSH 1.0 connections and any version before 2.0 is broken.

The device will accept 3des-cbc encryption. 3des is an outdated encryption algorithm.  
Finally, the Hash Message Authentication Code (HMAC) is SHA1 which has been deprecated for SSL since the end of 2015.

Continuing on:
Copy everything from ssh-rsa to ==.

From a terminal:
Create an empty file to paste the key into. I used nano to create a file in the .ssh folder in my home directory. I called the file ios.pub. Obviously a more descriptive name would be used in production.
nano ~/.ssh/ios.pub 

Paste the key into the file. MAKE sure that the key is a continuos string. You will probably have to remove a couple line feeds after you paste the key in. Save the file.

ssh-keygen uses arguments to select the action to perform. To calculate the fingerprint we will use the following argurments:
-f filename - Filename of the key file.
-l - Show fingerprint of key file. (lowercase L)

Run this command:
ssh-keygen -lf ~/.ssh/ios.pub
1024 73:e9:e6:e3:f6:52:22:05:fc:d7:5d:d8:d7:ef:12:4d /home/mhubbard/.ssh/ios.pub (RSA)

You can see that the fingerprint matches the one in the dialog so I know for sure that I am connecting to the correct device and no MiTM is present.

This will work for any rsa .pub file. For example, you can run ssh-keygen -lf /etc/ssh/ssh_host_rsa_key >> $HOME/keys.txt on your Linux/Mac rig and keys.txt will contain the fingerprints for your rig.

cat keys.txt
1024 c1:c8:63:45:ce:56:66:c3:1e:7c:58:d9:c2:8f:28:1e  root@1S1K-DO (DSA)
256 1d:24:82:44:4f:56:40:4e:53:44:92:7a:1b:e5:43:e0  root@1S1K-DO (ECDSA)
2048 2c:84:a5:cd:81:eb:71:0d:42:10:68:c0:fe:28:3c:d4  root@1S1K-DO (RSA)

Didier Stevens from SANS wrote a cool Python 2 script for calculating the fingerprint from the key - Calculating a SSH Fingerprint From a (Cisco) Public Key | Didier Stevens. His blog explains the various parts of the key, worth reading for sure.

References
SSH Mastery: OpenSSH, PuTTY, Tunnels and Keys (ebook) - An excellent reference on SSH.
What is a SSH key fingerprint and how is it generated?