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

Executing the same command against multiple devices

In the previous recipes, we have always only dealt with a single device. Quite often we have a fleet of similar devices that we want to configure in unison.

In this recipe, you will see how to programmatically open an SSH connection to multiple devices, issue the same command to all of them, and then save the output. We will again use this example to back up the running configuration of multiple devices.

Getting ready

Open your code editor and start by creating a file called exec_multiple.py. Next, navigate your terminal to the same directory that you just created the exec_multiple.py file in. Additionally, create a file called credentials.json. We will use this file to retrieve credentials such as the username and password of our devices.

How to do it...

Let's start by creating our credentials file. We will then read that file from our Python script, create clients for each of these devices, and finally execute a command while also saving the output back to our file:

  1. Import the required libraries, Paramiko and json:
    import json
    from paramiko.client import SSHClient
  2. Open up the credentials.json file and provide the credentials to your device(s) in the format shown in the following code. You can specify as many devices as you want:
    [
     {
       "name": "<insert a unique name of your device>",
       "host": "<insert the host of your device>",
       "username": "<insert the username>",
       "password": "<insert the password",
       "port": 22
     },
     {
       "name": "<insert a unique name of your device>",
       "host": "<insert the host of your device>",
       "username": "<insert the username>",
       "password": "<insert the password",
       "port": 22
     }
    ]
  3. Go back to your exec_multiple.py file. We will now open the JSON file in our Python script:
    credentials = {}
    with open("credentials.json") as fh:
         json.load(fh)
  4. Create a variable holding the command you want to execute. We will then loop over all the devices specified in our credentials.json file and create an SSH client object. Additionally, we will create an individual output file for each of our devices based on the name we specified in the JSON file:
    CMD = "show running-config"
    for cred in credentials:
         out_file_name = str(cred['name']) + ".txt"
         client = SSHClient()
         client.load_system_host_keys()
         client.connect(SSH_HOST, port=cred['port'],
                                  username=cred['username'],
                                  password=cred['password'])
         stdin, stdout, stderr = client.exec_command(CMD)
         out_file = open(out_file_name, "w")
         output = stdout.readlines()
         for line in output:
              out_file.write(line)
         out_file.close()
         client.close()
         print("Executed command on " + cred['name'])
  5. To run this script, go to your terminal and execute it with this:
    python3 exec_multiple.py

How it works...

In this example, we first create a JSON file containing the credentials and connection details for all of our devices. We can view this file as a type of inventory. In general, it is good practice to keep this information separate from the Python code that is acting upon it.

We then use the built-in json module to read the credentials file into a list of dictionaries that we can loop over.

Based on the credentials specified in the credentials file, we then open up a new Paramiko connection, execute the command, and write the output to a new log file, that is, by including the name we set for our device in the JSON file, which is unique for each of the devices.

With this, we can back up the running configuration of an entire fleet of devices from one simple script.

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 $19.99/month. Cancel anytime
Modal Close icon
Modal Close icon