Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Python Network Programming Techniques

You're reading from   Python Network Programming Techniques 50 real-world recipes to automate infrastructure networks and overcome networking challenges with Python

Arrow left icon
Product type Paperback
Published in Oct 2021
Publisher Packt
ISBN-13 9781838646639
Length 340 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Marcel Neidinger Marcel Neidinger
Author Profile Icon Marcel Neidinger
Marcel Neidinger
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Chapter 1: A Primer on Python 3 2. Chapter 2: Connecting to Network Devices via SSH Using Paramiko FREE CHAPTER 3. Chapter 3: Building Configuration Templates Using Jinja2 4. Chapter 4: Configuring Network Devices Using Netmiko 5. Chapter 5: Model-Driven Programmability with NETCONF and ncclient 6. Chapter 6: Automating Complex Multi-Vendor Networks with NAPALM 7. Chapter 7: Automating Your Network Tests and Deployments with pyATS and Genie 8. Chapter 8: Configuring Devices Using RESTCONF and requests 9. Chapter 9: Consuming Controllers and High-Level Networking APIs with requests 10. Chapter 10: Incorporating your Python Scripts into an Existing Workflow by Writing Custom Ansible Modules 11. Chapter 11: Automating AWS Cloud Networking Infrastructure Using the AWS Python SDK 12. Chapter 12: Automating your Network Security Using Python and the Firepower APIs 13. Other Books You May Enjoy

Loading local SSH configuration

When dealing with multiple different devices and connecting to them via SSH, it can be convenient to specify information such as the hostname, port, username, or identity file to use in a specific configuration file. The OpenSSH implementation stores this file in a file called config in the .ssh directory in your home directory (~/.ssh/config on macOS and Linux).

While we could copy and paste this information into our Python scripts or try to write a parsing function for the format ourselves, it is easier and more convenient to use Paramiko's SSH configuration parser.

In this recipe, you will see how to programmatically parse your SSHConfig file, extract the relevant information based on a host, and store it in a dictionary.

Getting ready

Open your code editor and start by creating a file called parse_config.py. Next, navigate your terminal to the same directory that you just created the parse_config.py file in.

You'll also need an SSH config file for the device you are trying to connect to. In this example, we will be using a config file that has the following content:

Host example
     Host <insert your host address here>
     User <insert your user here>
     Port <insert the port here>
     IdentityFile <insert the path to your private key here>

How to do it...

Let's start by importing the required libraries and defining the path to our SSH configuration:

  1. Import the Paramiko library:
    from paramiko.client import SSHClient
    from paramiko import SSHConfig
  2. Specify the path to your SSH config file and the name of your host as it appears in your SSH configuration (example in this snippet). We will populate all the other variables from the configuration we are reading:
    SSH_CONFIG = "<insert path to ssh config here>"
    SSH_HOST = "example"
  3. Create an SSHConfig object, which we just imported from Paramiko, and create a local file object with the path to our SSH configuration:
    config = SSHConfig()
    config_file = open(SSH_CONFIG)
  4. Next, we need to tell the SSHConfig object to load and parse the configuration file:
    config.parse(config_file)
  5. With the config parsed, we can now do a lookup on this configuration object to extract all information stored in the configuration itself. The lookup function will return a dictionary:
    dev_config = config.lookup(SSH_HOST)
  6. With our device configuration extracted from the SSH config we can go ahead and fill our connection details with what we have extracted from the SSH configuration file:
    client.load_system_host_keys()
    HOST = dev_config['hostname'],
    client.connect(HOST, port=int(dev_config['port']),
                         username=dev_config['user'],
                         key_filename=dev_config['identityfile'])
  7. With the connection established, we can do all the different things we discovered in previous recipes before finally closing the connection:
    client.close()
  8. To run this script, go to your terminal and execute it with this:
    python3 parse_config.py

How it works...

In this example, we use Paramiko's ability to parse an SSH configuration file to not define this information in multiple different locations.

We start by importing the SSHConfig class, in addition to the already established SSHClient class. Instead of manually specifying the host, username, and key file information, we now create a local file object that points to our SSH configuration.

With that file opened, we can now have Paramiko parse this configuration. The SSHConfig object now contains all the different information for each of the hosts. We can then do a lookup on our host – in this recipe, the host is called example – and extract all configuration variables that are known in the configuration file.

From that, we proceed to providing that information to the SSHClient. Instead of statically specifying it, we just access it from the dictionary that was returned by Paramiko when doing the lookup on the host.

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Python Network Programming Techniques
You have been reading a chapter from
Python Network Programming Techniques
Published in: Oct 2021
Publisher: Packt
ISBN-13: 9781838646639
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime
Modal Close icon
Modal Close icon