Monday, March 15, 2021

Apple MacBook Air M1 for Network Engineers Part 3

If you have been following along you now have macOS tuned up and some basic applications installed. If you need to read other parts of this series:

In part 3 we will continue installing applications.



Sublime text

One of the most popular editors for python developers. There is a free version that is fully functional but will ask you to buy once in a while and a paid version for $74.95. The license for the paid version lets you install it on all of your personal computers and it runs on Mac, Linux, and Windows so I purchased a license.

There are many tutorials on setting up Sublimetext for developers. 

realpython.com has some of my favorite tutorials:

Setting Up Sublime Text 3 for Full Stack Python Development

realpython.com also sells a package on python/sublimetext that includes detailed videos and pdfs on Sublimetext and Python for $59. I purchased it and was not disappointed. In fact, I signed up for the realpython.com membership for $100 per year.

Why is it so hard to find good and clear instructions on how to make Sublime more Python friendly? 

There are many reasons to give Sublime text a try if you are a network engineer, one of my favorites is that you can put a list of all the open files on the left side. This is much better than notepad ++ on Windows if you are working with several files at one time. You can even click and drag the files to change their order in the "Open Files" window. 




Installation

  • Download the package from www.sublimetext.com
  • Open the dmg file.
  • Drag to the applications folder
  • Set Sublimetext as the default editor for text documents.
  • In finder, locate a .txt file, right-click, get info, set "Open with" to Sublimetext.app.


Set the option to open files in the same window but a new tab.

Go to “Sublime Text” → “Preferences” → “Settings.”

Add the following property to your Sublime user configuration file:


{
	"open_files_in_new_window": false
}


The windows will look like this:



If there are already settings in the file, just add the 

"open_files_in_new_window": false 

between the starting and closing brackets on its own line. All of the lines except the last one have to have a comma at the end.

Save and close the two settings windows that opened. Now when you double click on a file it will open in the same window, in a new tab.

Reference

Sublime text open files same window

Zooming

To increase the text size
Press "⌘" and tap "+"

To decrease the text size
Press "⌘" and tap "-"


Returning to your default text size

Add the following to your keyboard bindings (found under Preferences)...

{ "keys": ["super+0"], "command": "reset_font_size" }

Super is the ⌘ key on macOS (ctrl on Windows/Linux)

super+0 would normally focus the 9th open tab in a Window, so you'll be overriding that behavior.

I found this great tip in the link below.

Reference

 

Using Snippets

This allows you to create snippets of text and insert them with a "trigger word" or from the tools menu. This site shows how to get started. There is an error in how to create a new snippet. Instead of tools, new snippet, it's tools, developer, new snippet.

quickly insert text and code with sublime text snippets

 Here is a sample snippet I made to start a config file for a cisco IOS-XE switch.

 

<snippet>
	<content><![CDATA[
no service pad
service tcp-keepalives-in
service tcp-keepalives-out
service timestamps debug datetime msec localtime
service timestamps log datetime msec localtime
service password-encryption
service linenumber
service sequence-numbers
service counters max age 5
no service dhcp

clock timezone PST -8 0
clock summer-time PDT recurring

no ip source-route
no ip gratuitous-arps

no ip domain lookup

login on-failure log
login on-success log
ipv6 nd raguard policy HOST_POLICY

spanning-tree mode rapid-pvst
spanning-tree portfast default

archive
 log config
  logging enable
  logging size 1000

interface  GigabitEthernet1/0/1
 switchport access vlan xxx
 switchport mode access
 switchport nonegotiate
 load-interval 30
 no cdp enable
 ipv6 nd raguard attach-policy HOST_POLICY
 storm-control broadcast level 1.00
 storm-control multicast level 1.00
 ip verify source
 exit

ip default-gateway x.x.x.x
ip forward-protocol nd
no ip http server
ip http authentication local
ip http secure-server
ip http secure-ciphersuite aes-256-cbc-sha ecdhe-rsa-aes-gcm-sha2 ecdhe-ecdsa-aes-gcm-sha2 
ip http tls-version TLSv1.2 
ip ssh rsa keypair-name SSH-KEYS
ip ssh version 2
ip ssh server algorithm mac hmac-sha2-256 hmac-sha2-512
ip ssh server algorithm encryption aes256-ctr aes192-ctr aes128-ctr
ip scp server enablebanner exec ^CC
*********************************************************
Switch Name:   xxxxxxxx
Description:   yyyyyyyyyyyyyyyy
*********************************************************
^C
$1
]]></content>
	<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>basic-cisco</tabTrigger>
	<!-- Optional: Set a scope to limit where the snippet will trigger -->
<scope>text</scope>
<description> Cisco start up </description>
</snippet>

I used "basic-cisco" as the trigger so I can type basic-cisco [tab] and sublime text inserts it and moves the cursor to a new line. Obviously, basic-HPE, basic-Arubacx will be next!

 I could also click tools, snippet, and pick it from the list.



The part of the snippet "<description> Cisco start up </description>" sets the description you see on the right of the men.


Open Sublime Text from the terminal

A lot of time I want to just type "subl <filename>" from the terminal to edit a file. I also want to use Sublime text for my git commit messages. Sublime provides instructions to set this up on macOS.

Setup

The first task is to make a symlink to subl. Assuming you've placed Sublime Text in the Applications folder, and that you have a ~/bin directory in your path, you can run:


ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" ~/bin/subl


The EDITOR environment variable

To use Sublime Text as the editor for many commands that prompt for input, set your EDITOR environment variable:

export EDITOR='subl -w'

Specifying -w will cause the subl command to not exit until the file is closed.

On my M1 I had to add the bin folder and this to the .zshrc file:

export PATH=$HOME/bin:$PATH
 

to make this work but now I can just type subl to start sublime text from the terminal.


Reference


Finding Differences

One really useful feature in Sublime text is the difference engine. An example will make it clear. 

In this file I changed the following:

interface 1/1-1/48
 
to

interface 1/1-1/48,2/1-2/48,3/1-3/48

In Sublime text, I right clicked over the line and selected "Show Diff Hunk"


Now Sublime text shows an orange bar on the left and the old string. Right clicking over the line again will show "Hide Diff Hunk", Revert Diff Hunk and show unsaved changes.

The "Show Unsaved Changes" will open a "Git" style windows and show you all the unsaved changes in the file.

--- /Users/mhubbard/GoogleDrive/01_Vector/network Refresh/Site-49/2930.txt  Fri Sep 17 09:58:10 2021
+++ /Users/mhubbard/GoogleDrive/01_Vector/network Refresh/Site-49/2930.txt  Sun Sep 19 16:21:35 2021
@@ -13,7 +13,7 @@
 time daylight-time-rule continental-us-and-canada
 time timezone -480
 spanning-tree
-interface 1/1-1/48
+interface 1/1-1/48,2/1-2/48,3/1-3/48
    rate-limit bcast in percent 1



The Network Tech Cisco plugin

This is a great open-source plug-in for Cisco network engineers. I have found that it does a reasonable job highlighting Aruba text and the network calculations work.

It highlights the keywords in the code, works with IOS, IOS-XR, Nexus, ASA, and ACE code. It also has:

  • code completion
  • Mask Conversions
  • Quick Info - Display subnet information
  • Format MAC Addresses by Colon, Dash or Dot
  • Password Decode - Decode type 7 passwords
  • Jumping - Quickly jump around large configuration using Symbols
  • Search for networks

Installation

Install Sublime Text's Package Control
Tools - Command Pallet
Install Package Control
<enter>




Install the package:
Tools - Command Pallet

 Package Control: Install Package
 [enter]
 Network Tech
[enter]

Set the syntax type

Open a file to edit or start a new file.

Supported configurations:

  • Cisco ASA
  • Cisco ACE
  • Cisco IOS
  • Cisco IOS XR
  • Cisco NXOS

Set the syntax from the command pallet

Tools - Command Pallet OR cmd+shift+p

Set Syntax: Cisco IOS <enter>


File extensions

If a configuration file has a specific file extension and is opened in Sublime Text, the syntax will be automatically be set:

  • Cisco ASA - *.cisco-asa - *.asa
  • Cisco ACE - *.cisco-ace
  • Cisco IOS - *.cisco-ios - *.ios
  • Cisco IOS XR - *.cisco-ios-xr - *.ios-xr
  • Cisco NXOS - *.cisco-nxos - *.cisco-nexus - *.nxos

Here is a screenshot of a highlighted configuration


Completions

Configuration snippets and autocompletion are suggested based on the syntax and configuration mode.

For example, I started typing errd and it suggested the following:


Mask Conversions

type a / and the conversion window will pop up. Once you find the mask you want press [enter]


In this example, pressing [enter] will insert 255.255.255.0

You can press ctrl+space to toggle between the netmask, wildcard mask and /

Jumping

One of the greatest features, if you are working on a large configuration file, is the ability to jump to commands that enter a configuration mode. For example, to jump to "interface vlan 20" press "cmd+r" and a dialog box will appear:


Type "vlan 20". 

In the search box select "interface Vlan20" and it will jump to that line. In this case, it's on line 685. 

You can search for more than just interfaces. Here I entered ip to find an access-list.


You can also jump to "line con" or "line vty"


Type 7 password decoding

Cisco type 7 passwords aren't hashed, they are "encoded' so they are reversible. Network Tech has a handy feature to decode them.

In a file that has a type 7 password:

  • Press Shift (⇧) + Command (⌘) + p to open the command palette
  • Enter "Network Tech: Decode Passwords"

You will see the passwords from the file, select the one you want to decode



In this example:

username cisco privilege 15 password 7 13061E01080355

It will ask if you want to save the password to the clipboard or display it. Here is what it looks like if you choose to display:


Listing network details

If you highlight an IP address and subnet mask, network tech list all the details for the subnet:




Reference

Network Tech


Compare Side-By-Side plugin


This package adds a simple side-by-side comparison tool to Sublime Text. I like MELD for comparing files but this control is very convenient since it's integrated into Sublime and works well.

Features
  • Easily select two tabs or selections to compare
  • Comparison results open in a new window
  • Empty lines added so common code lines up
  • Count number of lines changed
  • Highlighting of changed lines
  • Intra-line diff highlighting
  • Synchronized scrolling

Installation Options
  • Search for and install using Package Control (⌘+↑+P, “Install Package”)
  • (Preferences -> Browse Packages)

Usage Options
Right-click on a tab and select “Compare with…”
Right-click somewhere in the active view and select “Compare with…”
Right-click on a tab and select “Compare with active tab”
Highlight text, right-click -> “Mark selection for comparison”
Mark a second selection, then right-click -> “Compare selections”
Create two selections by holding CTRL, then “Compare selections”
From the command line: see README_COMMANDS.md
Jump to next: Alt+N, Jump to previous: Alt+P


Reference

Compare Side-By-Side


Using Regular Expressions

Sublime text supports regular expressions or Regex. This is a very powerful feature for searching and replacing text. I'm not going to lie to you, they are confusing but some simple concepts can get you a long way. 

Replacing vlan20 with vlan 20

I have been replacing a lot of Cisco equipment with Aruba. Usually, I don't try to copy Cisco configs over and modify, I would create a new Aruba template with the correct syntax and build a new configuration. 

Today I needed to add several SVIs from a Cisco to an Aruba. A template didn't make sense because it was just one switch, but I needed to update about 30 interface statements. Regex to the rescue! 

Here is what we will enter into the search/replace dialog:

find: interface ([vV]lan)(\d{1,3})
Replace: $1 $2

The () create a "capture group" that allows you to use the text it found in the replace window. The capture groups start at 1 and increment by 1. 

In this example, the first capture group matches on v or V.

The second matches on digits "\d" and the {1,3} matches 1, 2 or 3 digits.

In the replace dialog, click the icon on the far left that looks like a '.*". This puts the search box in regex mode.


Replacing text from the beginning of a line

Given a file with strings like this:

01_BRAD-MDF-AdminTL-STK1-2-config-output.txt:Gi2/0/10                       up             up       < Surv Serv 10.196.250.2 1c98.ec15.a338 > 


I just wanted the text starting with < and ending with >

This regex did the trick

^.*<

The "^" character means start at the beginning of the line
The "." means match one character
The "*" 0 or more of the preceding expression
The "<" was the first character that I wanted to keep.

The replace statement was just "<".

Here is what it looked like in sublime text:


Click the image to enlarge


I had 156 lines like this and with regex it took about 30 seconds to get the text I needed.


Regex quantifiers

Change Gi1/1 to Gi1/0/1 and repeat all other interfaces in the file

Find: (Gi[0-9])/([0-9]+)
Replace: $1/0/$2

Note:
You could also use (Gi[0-9])/([0-9]{1,2}) since the interfaces range from 1-48, 2 digits.

Quantifier  Meaning
A?          Match regular expression A zero or one times
A*          Match regular expression A zero or more times
A+          Match regular expression A one or more times
A{m}        Match regular expression A exactly m times
A{m,n}      Match regular expression A between m and n times (included)

The quantifiers are a powerful feature of regex. Here are some examples using interfaces.

The ? quantifier
Not that it matched just the first digit after the /


The * quantifier
Obviously there isn't a switch with 100,000,000 ports, I made that up to show that the "*" matches 0 or more times.


and here zero instances! Don't forget about 0 times, it can catch you by surprise.



The + quantifier
Here is an example of the "or more times"


Notice that unlike the "*" it doesn't match on 0 times


The {} quantifier
This quantifier allows you to pick exactly how many matches you want. Perfect for an interface.

Here is an example for matching the regex exactly 2 times



Here is an example for matching the regex 1 or 2 times. 




Reference


Speedtest-cli

https://github.com/sivel/speedtest-cli

Installation

Pip install speedtest-cli


speedtest-cli
Retrieving speedtest.net configuration...
Testing from Spectrum (71.84.93.96)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by Cox - Orange County (Orange County, CA) [51.76 km]: 27.113 ms
Testing download speed................................................................................
Download: 102.39 Mbit/s
Testing upload speed......................................................................................................
Upload: 21.24 Mbit/s

 

Iterm2

Installation
Download here: Iterm2
  • Open the zip file.
  • select "Automatically update".
  • move app to applications.
  • In Applications, select iTerm, right click, get info, Check "Open in Rosetta".
Iterm2 is a great terminal emulator. It has so many features you will have to read the documentation at:
iterm2 documentation

Onyx

Operating system utilities for macOS
Onyx Download
OnyX is a multifunction utility that you can use to verify the structure of the 
system files, to run miscellaneous maintenance and cleaning tasks, to 
configure parameters in the Finder, Dock, Safari, and some Apple applications, 
to delete caches, to remove certain problematic folders and files, 
to rebuild various databases and indexes, and more.
Download the package, move to the application folder


Ticker

Ticker - Stock ticker for the command line
Ticker Github page

Features

Live stock price quotes
Track value of your stock positions
Support for multiple cost basis lots
Support for pre and post market price quotes

Ok, this isn't network engineering related in anyway but you should be investing in the stock market.
Ticker is a fun little terminal app that lets you monitor stocks.

Installation
brew install achannarasappa/tap/ticker

Ticker uses ~/.ticker.yaml for configuration. Below is the default yaml file. Put stock symbols
in the watchlist area to watch them.


If you own stocks, put them in the Lots area. It's pretty self explanatory. Put the stock symbol
after symbol:, the quantity you own after quantity and the purchase cost after unit_cost.

Then open a terminal and type ticker [enter]
 
# ~/.ticker.yaml
show-summary: true
show-tags: true
show-fundamentals: true
show-separator: true
show-holdings: true
interval: 5
currency: USD
watchlist:
  - NET
  - TEAM
  - ESTC
  - BTC-USD
lots:
  - symbol: "ABNB"
    quantity: 35.0
    unit_cost: 146.00
  - symbol: "ARKW"
    quantity: 20.0
    unit_cost: 152.25
  - symbol: "ARKW"
    quantity: 20.0
    unit_cost: 145.35
















Apple MacBook Air M1 for Network Engineers Part 2

Updated April, 9th, 2023

Now that we have the macOS interface set up, it's time to install some applications! 

If you haven't read part 1, you can find it at the link below: 
Apple MacBook Air M1 for Network Engineers Part 1

Part 3 is now published and can be found at the link below:
Apple MacBook Air M1 for Network Engineers Part 3

Part 4 is now published and can be found at the link below:
Apple MacBook Air M1 for Network Engineers Part 4

Part 5 is now published and can be found at the link below:
Apple MacBook Air M1 for Network Engineers Part 5


Cisco Devnet

Cisco has jumped into network automation in a big way. Several of the tools in our list come from Cisco's Developer Workstation and Environment Setup webpage. This page has setup guides for Windows, Mac, and Linux. It does require a login. I used my CCO but it looks like you can use GitHub or Google also.

The exam requirements are listed here. This page also has some good tutorials on it, well worth a look. They have moved the Developer Workstation links to this page.

If you can't log in, here is a similar site on GitHub that doesn't require a login:

Developer Workstation and Environment Setup on GitHub

DevNet Certification Guide

I am working on the DevNet certification. I have documented most of the journey here

A terminal for Intel specific apps

Since this is a tutorial for the new M1 Apple silicon, we will set up a terminal using Rosetta2 so that any terminal apps that fail to run because of the ARM architecture can be used in an emulated Intel terminal.

I got this one from the Mac Geek Gab podcast. 

  • Open Finder, expand the Utilities folder, right-click on "Terminal" and select duplicate.
  • Rename the new shortcut to "Terminal-Intel" or something you like.
  • Right-click, select Get Info, check Open Using Rosetta.

Now all Intel-based terminal apps should work.


Adding your SSH keys to GitHub

Here is the github.com documentation for creating and adding your SSH keys to github.com. 

I used this YouTube tutorial to learn how to set up git to push my local repositories up to GitHub.com

Git and GitHub for Beginners - Crash Course


Here is a list of the apps that we will be installing:


Simplenote

This is a free (for now anyway) note-taking app from Automatic. It's available for Mac, IOS, Linux, Windows, and Android so it fits my work life perfectly since I use all of those operating systems. It syncs to the cloud using the Automatic servers. Automatic is the company behind WordPress so they know cloud!

Simplenote supports MarkDown so if you are going down the developer path you can sharpen your MD skills in Simplenote. It supports "Tags" which allows you to categorize notes. Not as good as Evernote notebooks but it's free and works for me.

Open the Mac App Store, search for Simplenote and install.


Termius - SSH Client

Termius isn't a mere SSH client, it's a complete command-line solution. Securely access Linux or IoT devices from your Android or iOS mobile device, as well as any Windows, macOS, or Linux computer. It is Mosh-compatible, providing excellent reliability on high-latency constantly changing connections.

Again, a tool that works on every platform! I got in on Termius during the beta and it was only $5.99 a year which was well worth it. The devices you create sync across all platforms so no matter what device you grab, it has all your hosts on it.

But the cost has gone up to $8.99 per month. You can do a trial to see if you like it. 

Open the Mac App Store, search for Termius and install.

Xcode

This is a huge application, 11.6GB! But if you want to use iPerf3 and many other terminal apps you need it. It is the tool used to write MacOS and IOS apps if you want to try your hand at that. 

Installation

Open the Mac App store, search for xcode and install.


Git and diff-so-fancy

Xcode includes git. After Xcode is installed you can run: 

git --version

to check what version of git is installed

xcode also installs python 3.x.


diff-so-fancy is an addition to git. It also works with the built in "diff" command. It adds better coloring and other features to the "git diff" command.

Installation


brew install diff-so-fancy

Once diff-so-fancy is installed enter the following commands in the terminal:

Configure git to use diff-so-fancy for all diff output:

git config --global core.pager "diff-so-fancy | less --tabs=4 -RFX"
git config --global interactive.diffFilter "diff-so-fancy --patch"

Improved colors for the highlighted bits

Enter the following commands in the terminal to set the colors:

git config --global color.ui true

git config --global color.diff-highlight.oldNormal    "red bold"
git config --global color.diff-highlight.oldHighlight "red bold 52"
git config --global color.diff-highlight.newNormal    "green bold"
git config --global color.diff-highlight.newHighlight "green bold 22"

git config --global color.diff.meta       "11"
git config --global color.diff.frag       "magenta bold"
git config --global color.diff.func       "146 bold"
git config --global color.diff.commit     "yellow bold"
git config --global color.diff.old        "red bold"
git config --global color.diff.new        "green bold"
git config --global color.diff.whitespace "red reverse"


To use diff-so-fancy with the built in diff command:

diff -u file-a file-b | diff-so-fancy

Reference


Serial

Published by Decisive Tactics.

Connect to routers, servers, firewalls, industrial control and IoT devices with ease. Serial includes built-in, reliable support for almost every serial device on the market, sparing you the hassle of finding, installing, and updating drivers.

Supported chipsets

This app is $39.99 on the Mac App Store. I was reluctant to spend that much on a serial app but a co-worker highly recommended it. Now that I have used it I agree! The built-in driver support is great. I haven't connected any USB to Serial cable that didn't just work. And, the app pops a connect dialog up as soon as you connect the USB. Very nice.

Version 2 has SSH support also. I haven't used it yet because I have so many devices in Termius and it runs on all my platforms. But if you don't want to pay the subscription to Terminus, Serial might be a good alternative.

Open the Mac App store, search for serial and install.


Homebrew

Homebrew provides access to many standard applications and packages but isn't optimized for large binary-based applications. As an extension to brew, cask is available for installing GUI applications. To list any available casks, you would use the --cask or --casks option with the brew list command. Use the --help option on brew commands to learn more:

 brew list --help

Installation

Start the Terminal-Intel and paste the following:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  • brew help to get started
  • brew -v to check the version

Show installed packages

┌─[mhubbard@HP8600-4] - [/private/tftpboot] - [2885]
└─[$] brew list                                                                                              [18:33:19]
==> Formulae
arp-scan	cdpr		iproute2mac	libuv		nghttp2		socat		watch
arping		cheat		jemalloc	lldpd		node		speedtest-cli	xz
asciinema	duf		lft		lsusb		openssl@1.1	sqlite		yadm
autojump	exa		libev		minicom		pcre2		tcl-tk
bat		gdbm		libevent	mpdecimal	python@3.9	tcptraceroute
brotli		icu4c		libnet		mtr		readline	ticker
c-ares		iperf3		libpcap		ncurses		sipcalc		ugrep

==> Casks
font-inconsolata-nerd-font	ngrok				unofficial-wineskin
google-chrome			openconnect-gui
mark-text			powershell

Further documentation: 


Oh My ZSH

macOS Big Sur uses zsh as the shell. Oh my zsh is an add-on that provides many additional features. You can read up on OMZ on their website. From the GitHub readme

A delightful community-driven (with 1800+ contributors) framework for managing your zsh configuration. Includes nearly 300 optional plugins (rails, git, OSX, hub, docker, homebrew, node, php, python, etc), over 140 themes to spice up your morning, and an auto-update tool so that makes it easy to keep up with the latest updates from the community.

This is a free, open-source project. If you find OMZ useful, please make a donation to the project.

I found this guy's blog and it has some useful tips for OMZ 

https://github.com/AidanGlickman/Dotfiles-Mac/blob/master/terminal/.zshrc

The link is to his .zshrc file. I took quite a bit out of his config to help me get started. 

Installation

By default, macOS doesn't create a configuration file for zsh. Before installing Oh My ZSH create one using

nano ~/.zshrc

Add 

ZSH_DISABLE_COMPFIX=true 

as the first line of ~/.zshrc file. This prevents a security notice on Mac. There isn't a Security issue, it's a false alert, but you can't continue the install until you do this. I had a little "Chicken and egg" issue. I added the line but Oh My ZSH overwrote the .zshrc file. I added it back in, reran the curl command and then it worked.

I'm coming from Ubuntu and BASH. I didn't think I would like zsh but with Oh My ZSH I am sold. I plan to install zsh with Oh My ZSH on my Unbuntu box I like it so much.

Now run the following shell script. NOTE: Normally it's not smart to run a shell script with curl from the Internet but you can review the script on the Oh My ZSH GitHub before running it.

sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

Now OMZ should be installed and working. 

Now we need to modify the .zshrc again.

Edit the .zshrc file 

nano ~/.zshrc

Press ctrl+w to search in nano and search for plugins

set plugins to:

plugins=(git zsh-completions zsh-autosuggestions zsh-syntax-highlighting)

Download the plugins

Look at the git clone, notice that it clones into your .oh-my-zsh/custom directory.

git clone https://github.com/zsh-users/zsh-completions ${ZSH_CUSTOM:=~/.oh-my-zsh/custom}/plugins/zsh-completions
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions


Some Additional Plugins that I find useful

Colored-man-pages

This plugin is very simple, all it does is colorize your man pages. It doesn't require a separate download, just add it to the plugins section in .zshrc

Here is what it looks like in action:


Aliases

Once you start creating aliases it's hard to remember all of them. Also, I didn't realize that the plugins create their own aliases.

This plugin simply lists all your aliases when you type acs. This one doesn't require a download either, just add it to the plugins section of .zshrc.

Here are a few lines output by aliases

┌─[mhubbard@HP8600-4] - [/private/tftpboot] - [3233]
└─[$] acs                                                                                                                                          [20:14:27]
[\gitk]
	gk = \gitk --all --branches
	gke = \gitk --all $(git log -g --pretty=%h)

[_default]
	- = cd -
	... = ../..
	.... = ../../..
	..... = ../../../..
	...... = ../../../../..
	_ = sudo
	afind = ack -il
	cat = bat
	ec = subl /Users/mhubbard/.zshrc
	egrep = egrep --color=auto --exclude-dir={.bzr,CVS,.git,.hg,.svn,.idea,.tox}
	exa1 = exa -lFT --group-directories-first
	extip = dig +short myip.opendns.com @resolver1.opendns.com
	fgrep = fgrep --color=auto --exclude-dir={.bzr,CVS,.git,.hg,.svn,.idea,.tox}
	ggpur = ggu


Git

This plugin provides a lot of aliases for git. If you aren't using git then there is no need to add it in. This plugin doesn't require a separate download either. Just add "git" to the plugins section.


ZSH Docker Aliases

An amazing collection of Docker aliases. The project GitHub has a complete listing of the aliases.

Installation

git clone https://github.com/akarzim/zsh-docker-aliases.git  ~/.oh-my-zsh/custom/plugins/zsh-docker-aliases
# then add `zsh-docker-aliases` to `plugins` in your .zshrc

Project GitHub


Here is what my plugins section looks like:

plugins=(git 
            zsh-completions
            zsh-autosuggestions
            zsh-syntax-highlighting
            history-substring-search
            colored-man-pages
            aliases
            zsh-docker-aliases
        )


There are many more plugins for zsh. They can be found here: ZSH Plugins webpage


Set the editors to use

Set nano as the editor when using ssh and VSCode when not.

Find the line below, uncomment the if statement. Change the EDITOR variable to nano and code. NOTE: We will install VScode next so don't run the zsh edit command until we finish installing VSCode.

Preferred editor for local and remote sessions

if [[ -n $SSH_CONNECTION ]]; then
  export EDITOR='nano'
  else
  export EDITOR='code'
 fi

Add some aliases to the .zshrc file

Obviously, aliases are very personal. You may not want the ones I have added, but they are good examples of how to create aliases if you want to create your own. Once you get used to aliases you will wonder how you got by without them.

Update - I found a blog on aliases and it suggested put a 2 charcter prefix on your aliases. That way you can type the 2 characters, hit tab twice, and all of your personal aliases will be listed. 


At the time of this writing, macOS includes Python 2.7. Since most of my tools are Python 3 I created these two aliases:

alias python=python3
alias pip=pip3

Show IP Address, Default GW, and name servers for wifi

alias ipen0='ifconfig en0 | grep "ether\|broadcast";netstat -nr | grep default | grep en0;cat /etc/resolv.conf | grep -v \#'

└─[$] ipen0 [19:55:49] ether 50:ed:3c:22:be:32 inet 192.168.10.143 netmask 0xffffff00 broadcast 192.168.10.255 default 192.168.10.254 UGScg en0 nameserver 1.1.1.1 nameserver 208.67.222.222 inet6 fe80::1c73:952b:1fdf:6cda%en0 prefixlen 64 secured scopeid 0xc

NOTE - On the M1 I had to add the \ character in front of the # symbol. Do not include it if you are on an Intel Mac.

┌─[mhubbard@HP8600-4] - [~/.ssh] - [3155]
└─[$] ipen0 
ether 50:ed:3c:22:be:32
inet 192.168.10.143 netmask 0xffffff00 broadcast 192.168.10.255
default            192.168.10.254     UGScg          en0
nameserver 1.1.1.1
nameserver 208.67.222.222


Show IP Address, Default GW, and name servers for en6

alias ipen6='ifconfig en6 | grep "ether\|broadcast";netstat -nr | grep default | grep en0;cat /etc/resolv.conf | grep -v \#'

NOTE - On the M1 I had to add the \ character in front of the # symbol. Do not include it if you are on an Intel Mac.

If you use a lot of different USB adapters you can use an alias with command line parameters. That way you just enter ipen<interface #> instead of having to create an alias for each interface.

alias ipenx='(){ifconfig en$1 | grep "ether\|broadcast";netstat -nr | grep default | grep en$1;cat /etc/resolv.conf | grep -v \# ;}'

NOTE - On the M1 I had to add the \ character in front of the # symbol. Do not include it if you are on an Intel Mac.

Example

I plugged in a USB 3.0 Ethernet adapter. It came up as en10.

ifconfig en10
en10: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=6467<RXCSUM,TXCSUM,VLAN_MTU,TSO4,TSO6,CHANNEL_IO,PARTIAL_CSUM,ZEROINVERT_CSUM>
ether 00:e0:4c:68:00:c2
inet6 fe80::18c6:afde:6f:b92f%en10 prefixlen 64 secured scopeid 0x17
inet 192.168.10.149 netmask 0xffffff00 broadcast 192.168.10.255
nd6 options=201<PERFORMNUD,DAD>
media: autoselect (1000baseT <full-duplex>)
status: active

ipenx 10

ether 00:e0:4c:68:00:c2
inet 192.168.10.149 netmask 0xffffff00 broadcast 192.168.10.255
default            192.168.10.254     UGSc          en10
nameserver 1.1.1.1
nameserver 208.67.222.222

I found this on stackexchange.com -  zsh alias with parameter

IPv6

I have started to work with IPv6 a lot lately. I added some code to the IP alias to show the IPv6 address along with the IPv4 address information. 

alias ipen0='ifconfig en0 | grep "ether\|broadcast";netstat -nr | grep default | grep en0;cat /etc/resolv.conf | grep -v \#;ifconfig en0 | grep inet6'

┌─[mhubbard@HP8600-4] - [~/.ssh] - [3154]
└─[$] ipen0                                                                                              
ether 50:ed:3c:22:be:32
inet 192.168.10.143 netmask 0xffffff00 broadcast 192.168.10.255
default            192.168.10.254     UGScg          en0
nameserver 1.1.1.1
nameserver 208.67.222.222
inet6 fe80::1c73:952b:1fdf:6cda%en0 prefixlen 64 secured scopeid 0xc


If you just want the IPv6 Address you can use this alias

alias ipen0='ifconfig en0 | grep "ether\|broadcast";netstat -nr | grep default | grep en0;cat /etc/resolv.conf | grep -v \#;ifconfig en0 | grep inet6 | awk -F " " '\''{print $2}'\'' | sed 's/%en0//''

┌─[mhubbard@HP8600-4] - [~/.ssh] - [3155]
└─[$] ipen0                                                                                                
ether 50:ed:3c:22:be:32
inet 192.168.10.143 netmask 0xffffff00 broadcast 192.168.10.255
default            192.168.10.254     UGScg          en0
nameserver 1.1.1.1
nameserver 208.67.222.222
fe80::1c73:952b:1fdf:6cda


# Return the public IP address you are using

alias extip="dig +short myip.opendns.com @resolver1.opendns.com"

# open ~/.zshrc in using the default editor specified in $EDITOR

alias ec="$EDITOR $HOME/.zshrc"

# reload ~/.zshrc after making changes to active the changes

alias sc="exec zsh"

Exit Nano (CTRL+X), Y to save, enter to exit.

Now refresh the .zshrc file
exec ~/.zshrc

You can now enter sc to refresh the .zshrc file!

Search History

Allow searching with the up arrow
Add "history-substring-search" to the plugins line:

plugins=(git zsh-completions zsh-autosuggestions zsh-syntax-highlighting history-substring-search)

After adding the search history to the plugin line, add this after the aliases
bindkey "^[[A" history-search-backward
bindkey "^[[B" history-search-forward

You can use the bindkey command to list all of your keyboard shortcuts in zsh.

Save and run the sc alias to reload oh my zsh


Oh My ZSH is now ready to run!

Type 
ip [enter]
and you should see a nicely formatted output of the wifi ip address, gw, and DNS servers.

ip
ether 50:ed:3c:22:be:32
inet 192.168.10.139 netmask 0xffffff00 broadcast 192.168.10.255
default            192.168.10.254     UGSc           en0
nameserver 1.1.1.1
nameserver 208.67.222.222

Type
extip [enter]

and you should see the public IP you are using.

To search command history, enter a couple letters and then press the UP arrow. It's a small thing but it will make a big difference in your daily use of the terminal.

Themes

Oh My ZSH has a lot of prebuilt themes that you can use. I like to have my cursor below the name and path since some of my paths get pretty long. I am currently using a theme named "duellj". Here is what it looks like:



The number after the path is the current history number. That is useful if you want to repeat a previous command using !<history number>. 

To change your theme just open the .zshrc file (ec if you added the alias) and find the entry for ZSH_THEME and set it to duellj:

ZSH_THEME="duellj"

The repository of themes is listed in the reference section below. 

Fixing Path issues in ZSH

After adding a lot of programs and customizing my .zshrc file I noticed that my path statement had several duplicate values. I found this article My PATH Variable is a Mess on the towardsdatascience.com site. It's worth reading even if your path isn't a mess and covers both macOS and Ubuntu!

TLDR - add "typeset -U PATH" as the last line in your .zshrc file

References for Oh My ZSH


The open command in terminal

A co-worker pointed this utility out to me and is useful when you are working in zsh. 

Open finder in the current directory

You can use the following to open finder in the folder that you are in:

open . 

That's the word "open" with a dot.

Open an application

open -a Wireshark
 
Will open Wireshark or switch to Wireshark if it is already running. You could do that easy enough using spotlight search so why is this useful? What if you wanted to open a second instance of Wireshark? If you use spotlight it will just switch to the open instance of Wireshark. 

With open you can use:

open -n -a Wireshark 

The -n opens a new instance. 

I created the following lines in my .zshrc file for opening a new Wireshark instance:

#allow opening multiple Wireshark windows
wireshark='open -n /Applications/Wireshark.app'


Open an application with a file

open edge_template.txt


will open edge_template.txt in whatever application you have associated with a .txt file.

Again, not earth-shattering, also, you can open every associated file in a folder:

open *.txt 

If you have projects organized in a way where you only have a handful of files of type in a folder this is useful.

Open a file in finder

I don't use this often but you can have "open" reveal a file in finder
open -R ~/networkRefresh/templates/edge_template.txt

Here is the result, finder is brought to the front with edge_tepm



VS Code 

Installation

Browse to code.visualstudio.com

Download the universal app and run the installer.

Customize

Open VS Code to display the main interface

Add VSCode to the MacOS path

 This is required to use code as the zsh editor and be opened from the terminal by typing code

Open the Command Palette (F1) and type "shell command" to find the "Shell Command: Install 'code' command in PATH" command:



This works as expected, but I have found that when I close code it removes the path. There must be a way to make it permanent but I haven't found it.

Add the Python extension

On the left, click the extensions view icon

Extension Icon

search for "python" and install:


"Python 
IntelliSense (Pylance)
Microsoft."

The latest version as of this writing is the December 2021 release. It includes "Pylance" which MS says provides robust and performant language features to Python users in Visual Studio Code. There is a link to the release page for Pylance in the reference section below.



There are hundreds of more extensions for Code. You can go to VSCode Marketplace to find more. 

This blog has some advice on what to add - vscode extensions to become a more productive developer

Themes

There a lot of custom themes available in the marketplace. Regardless of your tastes you will be able to find one that like. I put a link to a review of 10 of the most downloaded themes in the reference section below. I am currently using the github theme. It comes with several light and dark themes. I am using dark with high contrast. You can install it by clicking here.

This is what the Github Dark High Contrast theme looks like:


A great feature of VS Code for python is that it keeps track of your variable names and you can instantly jump to them. In the screenshot above, you can see that the cursor is on the variable "fabric". I jumped to fabric by clicking on the Icon that looks like a rectangle just above the code window. That generates a drop down list of variables in the program, select the one you want and it jumps to it.



How to disable telemetry reporting

Note: I leave this enabled so that MS can improve the product. If that is disagreeable to you, follow these steps to disable it.

VS Code collects usage data and sends it to Microsoft to help improve our products and services. Read our privacy statement and telemetry documentation to learn more.

If you don't want to send usage data to Microsoft, you can set the telemetry.telemetryLevel user setting to off.

From File > Preferences > Settings (macOS: Code > Preferences > Settings), search for telemetry, and set the Telemetry: Telemetry Level setting to off. This will silence all telemetry events from VS Code going forward.

Important Notice: VS Code gives you the option to install Microsoft and third-party extensions. These extensions may be collecting their own usage data and are not controlled by the telemetry.telemetryLevel setting. Consult the specific extension's documentation to learn about its telemetry reporting.

Sync Settings to multiple laptops

VS Code has a built-in method to sync settings between multiple machines. Obviously useful if you develop on more than one machine.

Click the gear icon on the bottom left of the screen, select "Turn on Settings Sync...". 






You will have to log in using a Github or MS account. 



A new browser window will open so that you can log in. After signing in, Settings Sync will be turned on and continue to synchronize your preferences automatically in the background. 

Syncing a second laptop

Since syncing can involve conflicts you will have to make a choice when you set up the second laptop.



Reference


Powershell

Microsoft open-sourced Powershell a while back. I usually install it on Linux, I have found that scripts that don't access a drive letter usually work on Linux. There is one script from Black Hills Information Security that I use all the time. You can read about it here

1..1024 | % {$test= new-object system.Net.Sockets.TcpClient; $wait = $test.beginConnect("allports.exposed",$_,$null,$null); ($wait.asyncwaithandle.waitone(250,$false)); if($test.Connected){echo "$_ open"}else{echo "$_ closed"}} | select-string " "


Installation

brew install --cask powershell

After the install finishes you will need to update the help file.

update-help

Powershell is installed into this folder:
/usr/local/microsoft/powershell/7


Running Powershell
Open a new tab in iTerm2 and enter:
pwsh 

Here is a link to a simple PowerShell script I wrote to create DHCP reservations for printers. It ran perfectly on macOS:

Today I needed to create DHCP reservations for some Access Points. I had the script above but I wanted to read the data from a CSV file. Here is the script modified to read the data from a CSV file.

param([string]$server = "server", [string]$scope = "scope")
$a = Import-Csv DHCP.csv
foreach ($item in $a) {
$ip=$($item.IP)
$mac=$($item.MAC)
#remove colons since MS DHCP can't deal with a real mac address
$mac=$mac-replace'[:]'
$name = $($item."AP-Name")
write-host "netsh dhcp server $server scope $scope add reservedip $ip $mac $name"
}


I created an Excel sheet like this:


Notice that the first MAC address doesn't have colons. When I get an asset sheet from my office the MAC addresses don't have colons. The script removes colons if they are there.


Here is the output:

PS /Users/mhubbard/GoogleDrive/Test/configs> ./dhcp-csv.ps1 -server 192.168.10.221 -scope 10.112.105.0
netsh dhcp server 192.168.10.221 scope 10.112.105.0 add reservedip 10.112.105.100 a44c1138fa5b AP1
netsh dhcp server 192.168.10.221 scope 10.112.105.0 add reservedip 10.112.105.101 04d5900e779b AP2
netsh dhcp server 192.168.10.221 scope 10.112.105.0 add reservedip 10.112.105.102 b0faebdde8a6 AP3
netsh dhcp server 192.168.10.221 scope 10.112.105.0 add reservedip 10.112.105.103 a44c1138fa59 AP4
netsh dhcp server 192.168.10.221 scope 10.112.105.0 add reservedip 10.112.105.104 5057a86e4b49 AP5

I know that you could do the same thing in Python. But most customers are on Windows and Python isn't installed by default but PowerShell is. If you use PowerShell you can give the script to any Windows user and they can run it.

Note: Guido Von Rossum, the inventor of Python, now works at Microsoft! Maybe Python will be installed by default in the future.

The PowerShell ISE isn't available on macOS but Microsoft has a plugin for Visual Studio Code. The link to how to install the plugin is in the references below.

This article gives some tips on writing PowerShell scripts that work on Windows/Mac/Linux

VMWare PowerCLI
One advantage of Microsoft open sourcing PowerShell is that VMWare's PowerCLI modules can be used on macOS and Linux! From inside PowerShell run the following to install PowerCLI:

Install-Module -Name VMware.PowerCLI

You will be prompted that the repository isn't trusted. The modules are being pulled from the PowerShell gallery. If you don't trust it you can use the link below to download the raw files and inspect them before installing them. You can also use that method to install them on a server without Internet access.

Zip file with the modules: VMware PowerCLI
VMWare's installation guide is here: Install PowerCLI
VMWare's PowerCLI User's Guide can be downloaded here: PowerCLI 12.1.0 User's Guide

Since VMWare is the 800 pound gorilla of Enterprise virtualization, there is a vast amount of resources on the Internet. This blog is a great introduction to installing and using PowerCLI


Connecting to a vCenter server

Connect-VIServer -Server 10.23.112.235 -Protocol https -Username 'Adminis!ra!or' -Password 'pa$$word'

 

PowerShell path on macOS

For some reason the PowerShell install didn't add the path. PowerShell is installed at:

$HOME/.local/share/powershell

and scripts are installed at

$HOME/.local/share/powershell/Scripts

From inside the PowerShell terminal, you can use:
 
$Env:PATH 

To display the current path.

You can add the path to the PowerShell profile using:

nano $PROFILE

To open the profile, then:

$Env:PATH += ":$HOME/.local/share/powershell/Scripts"

to add the path. You will need to close and re-open the PowerShell terminal.

PowerShell Gallery

Microsoft maintains a "Gallery" of PowerShell scripts. Some are written by Microsoft, and others are provided by the community. 

MS provides quite a bit of documentation for the Gallery. This link is a good place to start

PowerShell Gallery

You can view the repositories that are installed in PowerShell using "Get-PSRepository"


As you can see, I just have the default repository from Microsoft. And you can see that the Installation Policy is untrusted. When you install a script from the Gallery you will be prompted that the repository is untrusted.



I entered y to allow the installation to continue. You can use the "Set-PSRepository" command to trust the repository. I chose not to since there are a lot of community-provided scripts and I don't know how deep MS looks at the code.


DSC - Desirable State Configuration
I saw a lot of scripts listed at "DSC" which I found stands for Desirable State Configuration. I didn't dig into it since I don't build Windows machines, but they appear to be scripts that install roles and configure Windows per MS best practices.


Finding Scripts
You can go to the PowerShell Gallery Homepage and browse/search for scripts. I went there and searched for "dhcp". It returned two pages of scripts! 

You an also search from the terminal:

Find-Script 
with no arguments will return all scripts, but there are so many you will have to put them into a text file to be useful.

If you know the EXACT name of the script you can use the -name argument. In this example I knew that the script I wanted to install is called "Ping-MultipleHosts"



I have found that the community scripts are hosted on GitHub and there is a link on the Gallery page that takes you to the project homepage. I like to go there and review the code before I install it. More to learn than to see if it's malicous.

Once you find the script in the gallery run "Install-Script":
Install-Script Ping-MultipleHosts

This will download the script to:

$HOME/.local/share/powershell/Scripts

ls $HOME/.local/share/powershell/Scripts
InstalledScriptInfos Ping-MultipleHosts.ps1

Then execute the script:



There is a lot more to PowerShell and now that it works on Linux/Mac, it is well worth the time to learn some. I am working on some PowerShell tools that will aid in deploying Dynamic Arp Inspection on switches. I created this GitHub repo if you are interested in looking at them.



Reference


Autojump

https://github.com/wting/autojump

autojump is a faster way to navigate your filesystem. It works by maintaining a database of the directories you use the most from the command line. Directories must be visited first before they can be jumped to.

Installation

brew install autojump

Add

[ -f /usr/local/etc/profile.d/autojump.sh ] && . /usr/local/etc/profile.d/autojump.sh

To the .zshrc file

Remember, you can type ec [enter] to open the .zshrc file in VScode.

Example, from my home folder
j pro
/Users/mhubbard/GoogleDrive/Python/Scripts/prod
➜ prod git:(master) ✗

NodeJS

If you are planning to get Cisco's DevNet cert you need NodeJS.

 brew install node

A lot of information scrolls past during the install. I didn't do any of the suggested modifications to my path. I saved the messages so if I run into issues I can follow the suggestions.


Postman

Postman is a tool for working with RESTful APIs. You will need it if you are working on the Cisco DevNet cert or just using a REST API on a switch.

Download Postman

Install the package as normal. 

Open Postman and follow the instructions to create an account


Ngrok

From the ngrok website

Spend more time programming. One command for an instant, secure URL to your localhost server through any NAT or firewall.

You will need ngrok if you are working on the Cisco DevNet cert

brew install --cask ngrok

Verify

 ngrok http 8000

ngrok by @inconshreveable                                                                                     (Ctrl+C to quit)

Session Status                online

Session Expires               1 hour, 59 minutes

Version                       2.3.35

Region                        United States (us)

Web Interface                 http://127.0.0.1:4040

Forwarding                    http://441c7dc90556.ngrok.io -> http://localhost:8000

Forwarding                    https://441c7dc90556.ngrok.io -> http://localhost:8000


Connections                   ttl     opn     rt1     rt5     p50     p90

                              0       0       0.00    0.00    0.00    0.00


Now start a python http server on port 8000 in a new iTerm tab

python http.server 8000

Open a browser and enter

http://441c7dc90556.ngrok.io

You will need to allow Python to accept incoming connections in System Preferences, Security & Privacy. The easiest way to do that is to stop/start the firewall after you start the Python web server. It will ask if you want to allow incoming connections to the python server.

This blog has some demos on ngrok. It's a little dated but still useful.

Ngrok with macOS



Google Chrome

brew install --cask google-chrome

Chrome is a universal app now.



Open Connect

An open source VPN client that can be used to connect to Cisco DevNet labs.

You will need Open Connect if you are working on the Cisco DevNet cert

Brew install --cask openconnect-gui



Minicom

minicom is an terminal app that allows you to connect to USB to Serial cables and console into devices. 

brew install minicom

To set the "Meta" key to be the Mac Option key

Terminal > Preferences... (or type ⌘+,). Then, Profiles > Keyboard and check the box Use Option as Meta key.

https://www.shell-tips.com/mac/meta-key/

Before starting minicom you need to know the name of the com port that macOS assigned to your USB adapter. Open a terminal and enter:

ls -l /dev/tty.usb*

You should see something like this:

ls -l /dev/tty.usb*

crw-rw-rw-  1 root  wheel    9,   6 Mar 15 15:54 /dev/tty.usbserial-1140

The first time you run minicom use

minicom -s 

to enter setup mode. Scroll down to "Serial port setup" and press enter.

Use /dev/tty.usbserial-1140 for option A - Serial Device.


If you use a different USB cable you can start with:

minicom -D /dev/tty.usbserial-(name of new cable)

Logging

You can use -C (path/filename) to save a log.


That's enough for one blog! In the next installment, I will cover more networking tools like iPerf3, Wireshark, arp-scan, etc. Be sure to check back soon.