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

Reading the output of an executed command

In the previous recipe, we saw how to first connect to a device and then execute a command. So far, we have ignored the output though.

In this recipe, you will see how to programmatically open an SSH connection, send a command, and then write the output of that command back to a file. We will use this to back up a running configuration.

Getting ready

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

How to do it...

Let's start by importing the Paramiko library and create a client object as seen in the last recipe. Then execute a single command of your choice on this device and save the output:

  1. Import the Paramiko library:
    from paramiko.client import SSHClient
  2. Specify the host, username, and password. You can name these variables however you like. In the Python community, it has become a standard to uppercase these global variables:
    SSH_USER = "<Insert your ssh user here>"
    SSH_PASSWORD = "<Insert your ssh password here>"
    SSH_HOST = "<Insert the IP/host of your device/server here>"
    SSH_PORT = 22 # Change this if your SSH port is different
  3. Create an SSHClient object, which we just imported from Paramiko:
    client = SSHClient()
  4. While we have created our client object, we have not yet connected to the device. We will use the connect method of the client object to do so. Before actually connecting, we will need to make sure that our client knows the host keys:
    client.load_system_host_keys()
    client.connect(SSH_HOST, port=SSH_PORT,
                             username=SSH_USER,
                             password=SSH_PASSWORD)
  5. Finally, we can use the client to execute a command. Executing a command will return three different file-like objects to us representing stdin, stdout, and stderr:
    CMD = "show running-config" 
    stdin, stdout, stderr = client.exec_command(CMD)
  6. We will use the stdout object to retrieve what the command has returned:
    output = stdout.readlines()
  7. Next, we write the output back to a file:
    with open("backup.txt", "w") as out_file
        for line in output:
            out_file.write(line)
  8. To run this script, go to your terminal and execute it with this:
    python3 read_out.py

How it works...

In this example, we first created a new client as seen in the previous example. We then used the exec_command() method to execute a command of our choice. We then used the returned file-like object for the standard out to read everything that our remote device printed into the standard out and write it into a file.

A file-like object in the context of Python is an object that offers the same functions as a file object. When using the open() function to create a new file object to read/write from locally, we are offered some functions such as write() or readlines(). These functions allow us to read or write from or to a file. A file-like object offers the same functions and can thus be used as if it was a remote file. We use the readlines() function on the stdout object to read everything returned – in this example, the running configuration of our device – and write it line by line to a local file.

There's more...

If you prefer to just see the output of your command instead of writing it to a file, you can also use the following construct, instead of the code provided in step 7 of the recipe, to print out your entire configuration:

for line in output:
    print(line.strip())  

The strip() method used in the preceding example will delete any unnecessary leading or trailing whitespaces.

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