What you need for this bookWho this book is for Sections Getting ready How to do it… How it works…There's more…See alsoConventions Reader feedback Customer support Downloading the exampl
Trang 2Automate network devices on Juniper's operating system
Adam Chappell
BIRMINGHAM - MUMBAI
JUNOS Automation Cookbook
Trang 3JUNOS Automation Cookbook
Copyright © 2017 Packt Publishing
All rights reserved No part of this book may be reproduced, stored in a retrieval system, ortransmitted in any form or by any means, without the prior written permission of the publisher,except in the case of brief quotations embedded in critical articles or reviews
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented However, the information contained in this book is sold without warranty,either express or implied Neither the authors, nor Packt Publishing, and its dealers and
distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book
Packt Publishing has endeavored to provide trademark information about all of the companiesand products mentioned in this book by the appropriate use of capitals However, Packt
Publishing cannot guarantee the accuracy of this information
First published: September 2017
Trang 5About the Author
Adam Chappell first cut his teeth in the networking world in 1995 after an opportunity in
Finchley, North London, at what would become one of the pioneering dial-up Internet ISPs in theUnited Kingdom His early forays into network automation generally involved cron, Perl, expect,and a healthy dose of hope and luck As the commercial networking market matured, he joinedInteroute to develop one of the first large-scale European MPLS networks, leading the market inthe provision of private packet networking
Adam was responsible for Interoute's unique network automation technology that seamlesslystitches together industry-standard MPLS VPNs and private cloud compute logical networks.Currently, he works in the thriving technology development team at Interoute, between Londonand Prague, focusing on network technologies, software, and security
I’d like to say a very big thankyou to the team at Packt Publishing for their support with thisbook Meeta, Abhishek, Nipu, and Manish, they all deserve my salute for their professionalismand dedication to the effort of putting a book together I owe a debt of gratitude to some of mycolleagues at Interoute, including Gary for his efforts at making Juniper VRR and VMX dance tohis tune, Ivan for tolerating my experimentation on the live network, and Shish and Alistair for
my inane questions at all hours But writing a book like this doesn’t come without tolerance andsupport from those close to you So, most importantly, I would like to say a big thank you to mywife, Mila, and my children, Maty and Tobi, for their extended patience
Trang 6About the Reviewer
Mohammad Mohsinul Malik is currently working as an advanced service consultant with
Juniper Networks, Malaysia
He completed his engineering from Jamia Millia Islamia University, New Delhi, and has around
11 years of experience in the IP networking industry He has extensive hands-on experience inlarge enterprise networks and tier 1 and tier 2 service providers
His interests include SDN, NFV, network automation, IoT, network security, digital forensics,and cloud technologies
Malik has earned the networking industry’s most sought-after certifications and is among an elitegroup of engineers in the world who hold such diverse certifications
He has active triple JNCIE (SP, ENT, SEC), triple JNCSP (SP, ENT, SEC), triple JNCDS
(WAN, DC, SEC), JNCIP-DC, JNCIS-QFabric, and JNCIS-SDNA from Juniper Networks.Also, he has earned other vendors certifications, such as CCIE-SP, CCNP-R&S, CISSP,
PCNSE7, MCSE, BCEFP, SCP, and so on
He also likes exploring new technologies and spends his spare time in his home lab, playing withsoftware code
Trang 7For support files and downloads related to your book, please visit www.PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and ePubfiles available? You can upgrade to the eBook version at www.PacktPub.comand as a print bookcustomer, you are entitled to a discount on the eBook copy Get in touch with us at
service@packtpub.com for more details
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for arange of free newsletters and receive exclusive discounts and offers on Packt books and eBooks
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt Mapt gives you full access to all Packt booksand video courses, as well as industry-leading tools to help you plan your personal developmentand advance your career
Trang 9Customer Feedback
Thanks for purchasing this Packt book At Packt, quality is at the heart of our editorial process
To help us improve, please leave us an honest review on this book's Amazon page
at https://www.amazon.com/dp/1788290992
If you'd like to join our team of regular reviewers, you can e-mail us
at customerreviews@packtpub.com We award our regular reviewers with free eBooks and videos inexchange for their valuable feedback Help us be relentless in improving our products!
Trang 10Table of Contents
Preface
What this book covers?
What you need for this bookWho this book is for
Sections
Getting ready How to do it…
How it works…There's more…See alsoConventions
Reader feedback
Customer support
Downloading the example code Downloading the color images of this book Errata
PiracyQuestions
1 Configuring JUNOS through NETCONF
Introduction
JUNOS NETCONF over SSH setup
Getting ready How to do it
How it works
There's more
See alsoUsing NETCONF to apply configuration changesGetting ready
Trang 11How it works
Processing NETCONF with Python
Getting ready How to do it
How it works
Processing NETCONF with Node.js
Getting ready How to do it
How it works
There's moreMaking REST API calls to Junos with Python
How it works
Managing passwords safely
Getting ready How to do it
How it works
Using XPath predicate expressions
Getting started How to do it
How it works
Working with regular expressions
Getting ready How to do it
How it works
Working with IP addresses
Trang 12Getting ready How to do it
How it works
There's moreDebugging SLAX scripts
Getting ready How to do it
How it works
There's moreMaking custom show commandsGetting ready
How to do it
How it works
Making configuration changes
Getting ready How to do it
Getting ready How to do it…
How it works…There's more
Custom responses to an event
Getting ready How to do it…
How it works…There's more
Dealing with a flapping interfaceGetting ready
How it works…
Debugging event scripts
Getting ready
Trang 13How it works…
There’s moreExploring the XML RPC using PyEZ
Getting ready How to do it…
There’s moreUsing tables and views
Getting ready How to do it…
How it works…There's more
Using custom tables and views
Getting ready How to do it…
Getting ready How to do it…
Trang 14Graph principlesGraph data How
to do it
Instantiating the template Drawing the graph Running the example graphHow it works
Instantiating the templateDrawing the graph Extracting
graphs from ISISGetting started
ISIS primerHow to do it
How it works
Extracting graphs from OSPF
Getting readyOSPF primerHow to do it
How it works
Extracting graphs from MPLS VPNs
Getting readyBGP MPLS VPN primer How to do it
SSH File TransferJUNOS OS event policy Web server application Web client applicationThere's more
Monitoring interface performance
Getting readyObject-oriented primer for Node.js How to do it…
Server application Web client application Setting up and RunningHow it works
Trang 15Server applicationWeb client applicationThere's more Monitoring
system healthGetting ready How to do it
Server applicationWeb client application How it works
Server application Client application Running the applicationThere's more
Monitoring MPLS LDP statistics
Getting ready How to do it
Server applicationWeb client application How it works
Server application Web client application
Getting ready How to do it
How it works
Applying anti-spoofing filters
Getting ready How to do it
How it works
There's moreOperating a distributed ACL function
Getting ready How to do it
Trang 17What Juniper has capitalized on, however, is a universal configuration management frameworkthat powers all of the varied aspects of Junos and that is based on inter-communication usingXML The choice of XML puts Junos in a prime position for integrating its capabilities intolarger systems by exposing its XML machine-to-machine interfaces—so-called RPCs or RemoteProcedure Calls—to automation applications.
In this book, we take a recipe-based approach to investigating and exploring the automationtechnologies surrounding Junos and provide some examples of how to tackle common networkrequirements
Trang 18What this book covers?
Chapter 1, Configuring JUNOS through NETCONF, explores the NETCONF standard originally
defined in RFC 4741, specifically, how it’s used over SSH to communicate with Junos devices
We will work through some practical examples of communicating with Junos programmaticallyfrom several technologies
Chapter 2, Working with the Junos REST API, explores the relatively new REST interface with
Junos and how to make use of it in HTTP and HTTPS environments We will develop twosample REST clients that interact with Junos
Chapter 3, Using SLAX to Write Op Scripts, explores Juniper’s SLAX technology for
manipulating the XML representations used by the foundations of Junos We will look at how touse SLAX as a macro language to make use of remote procedure calls and produce customized,filtered output
Chapter 4, Event Programming, builds upon the SLAX expertise and leverages the capability to
be proactive and respond to events We’ll develop scripts to deal with common network
situations and even a make shift routing protocol
Chapter 5, Automating Junos with PyEZ, focuses on the Juniper extension module to Python,
PyEZ, and its utility in programmatically working with Junos You'll learn about PyEZ
primitives, such as facts, views, and tables, and get a taste of using YAML to write Jinja2
templates
Chapter 6, Advanced Visualization Applications, helps us visualize some of the aspects of our
Junos network We’ll build a basic graph utility for extracting information and then we'll use apopular rendering engine to visualize elements of our network, such as routing protocols
Chapter 7, Monitoring and Maintaining Junos, looks at ways of monitoring what happens on our
Junos network We’ll build a tool to monitor configuration changes as well as look at how wecan graphically monitor interface usage and other resources
Chapter 8, Security Applications, looks at how we can use automation technologies to maintain
the security of our networks We’ll build commit scripts to vet configuration changes and look atBGP prefix filtering and anti-spoofing protection
Chapter 9, Extending JUNOS with Ansible, explores how we can use the popular Ansible IT
automation framework in conjunction with Junos as part of a wider enterprise orchestrationsystem
Trang 19What you need for this book
In order to make use of the examples in this book, you’ll need a Unix-based management device,which can be your laptop or a virtual machine on your laptop, and access to a Junos platform Insome cases, it’s possible to run Junos in a virtual environment, such as with Juniper’s latest vMXdevelopments or with vRR - virtual route reflector Finally, if all else fails, you can also build anolive But I'm not going to tell you how to do that!
Trang 20Who this book is for
This book is for you if you’re a network engineer or operator with enthusiasm for networktechnology and a persistent thirst for wanting to know how you can get Juniper routers andswitches to do more with less
Trang 21In this book, you will find several headings that appear frequently (Getting ready, How to doit…, How it works…, There's more…, and See also) To give clear instructions on how tocomplete a recipe, we use these sections as follows:
Trang 22Getting ready
This section tells you what to expect in the recipe, and describes how to set up any software orany preliminary settings required for the recipe
Trang 23How to do it…
This section contains the steps required to follow the recipe
Trang 24How it works…
This section usually consists of a detailed explanation of what happened in the previous section
Trang 25There's more…
This section consists of additional information about the recipe in order to make the reader moreknowledgeable about the recipe
Trang 26See also
This section provides helpful links to other useful information for the recipe
Trang 27In this book, you will find a number of text styles that distinguish between different kinds ofinformation Here are some examples of these styles and an explanation of their meaning.Code words in text, database table names, folder names, filenames, file extensions, pathnames,dummy URLs, user input, and Twitter handles are shown as follows: In this case, the RPC that
Any command-line input or output is written as follows:
adamc@router> show configuration interfaces em0.0 | display xml
<rpc-reply xmlns:JUNOS="http://xml.juniper.net/JUNOS/
15.1F6/JUNOS">
New terms and important words are shown in bold.
Warnings or important notes appear like this
Tips and tricks appear like this
Trang 28Reader feedback
Feedback from our readers is always welcome Let us know what you think about this book-whatyou liked or disliked Reader feedback is important for us as it helps us develop titles that youwill really get the most out of To send us general feedback, simply e-mail feedback@packtpub.com,and mention the book's title in the subject of your message If there is a topic that you haveexpertise in and you are interested in either writing or contributing to a book, see our authorguide at www.packtpub.com/authors
Trang 29Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you toget the most from your purchase
Trang 30Downloading the example code
You can download the example code files for this book from your account at
http://www.packtpub.com If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support, and register to have the files e-mailed directly to you Youcan download the code files by following these steps:
1 Log in or register to our website using your e-mail address and password
2 Hover the mouse pointer on the SUPPORT tab at the top
3 Click on Code Downloads & Errata
4 Enter the name of the book in the Search box
5 Select the book for which you're looking to download the code files
6 Choose from the drop-down menu where you purchased this book from
7 Click on Code Download
You can also download the code files by clicking on the Code Files button on the book's
webpage at the Packt Publishing website This page can be accessed by entering the book's name
in the Search box Please note that you need to be logged in to your Packt account Once the file
is downloaded, please make sure that you unzip or extract the folder using the latest version of:WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at
https://github.com/PacktPublishing/JUNOS-Automation-Cookbook We also have other codebundles from our rich catalog of books and videos available at
https://github.com/PacktPublishing/ Check them out!
Trang 31Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in
this book The color images will help you better understand the changes in the output You can
download this file from
https://www.packtpub.com/sites/default/files/downloads/JUNOSAutomationCookbook_ColorImages.pdf
Trang 32Although we have taken every care to ensure the accuracy of our content, mistakes do happen Ifyou find a mistake in one of our books-maybe a mistake in the text or the code-we would begrateful if you could report this to us By doing so, you can save other readers from frustrationand help us improve subsequent versions of this book If you find any errata, please report them
by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the ErrataSubmission Form link, and entering the details of your errata Once your errata are verified, yoursubmission will be accepted and the errata will be uploaded to our website or added to any list ofexisting errata under the Errata section of that title To view the previously submitted errata, go
to https://www.packtpub.com/books/content/support, and enter the name of the book in thesearch field The required information will appear under the Errata section
Trang 33Piracy of copyrighted material on the Internet is an ongoing problem across all media At Packt,
we take the protection of our copyright and licenses very seriously If you come across anyillegal copies of our works in any form on the Internet, please provide us with the locationaddress or website name immediately so that we can pursue a remedy Please contact us at
copyright@packtpub.com with a link to the suspected pirated material We appreciate your help inprotecting our authors and our ability to bring you valuable content
Trang 34If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com,and we will do our best to address the problem
Trang 35Configuring JUNOS through NETCONF
In this chapter, we will cover the following recipes:
JUNOS NETCONF over SSH setup
Making NETCONF RPC requests and replies
Using NETCONF to apply configuration changes
Processing NETCONF using classic Expect/TCL
Processing NETCONF with Python
Processing NETCONF with Node.js
Discovering NETCONF RPCs
Trang 36The Network Configuration Protocol (NETCONF) standard, defined most recently in RFC
6241, allows a network management application to access a JUNOS OS (or other vendor)
network element through the use of a series of Remote Procedure Calls (RPCs) carried over a
serialized XML transport
For programmatic access to JUNOS OS devices, this method is preferable for the use of rawcommand-line processing, since the data format is structured, precise, and suitable for
unambiguous machine reading
In this chapter, we investigate how to setup NETCONF access to JUNOS OS devices and thenlook at how to make use of that from common programming platforms
Trang 37JUNOS NETCONF over SSH setup
In this recipe, we'll prepare a JUNOS OS router for interaction using the NETCONF service Wecan do this in one of two ways:
Using NETCONF-over-SSH on dedicated TCP port 830,
Using NETCONF inline with mainstream SSH communications, on TCP port 22
We'll set up secure SSH keys and a dedicated username for an automation application Then we'llconfigure the systems services hierarchy within the Junos OS for the specific method
Trang 38Getting ready
In order to complete this recipe, you need access to a JUNOS OS router, switch, or firewall, and
a general-purpose Linux/UNIX management host from which to control it
Trang 392 Generate SSH keys Generate a public/private key pair using the SSH utility, ssh-keygen:
unix$ ssh-keygen -C "JUNOS Automation" -f JUNOS_auto_id_rsa
Generating public/private rsa key pair.
Enter file in which to save the key (.ssh/id_rsa):
JUNOS_auto_id_rsa
Enter passphrase (empty for no passphrase): <type nothing here>
Enter same passphrase again: <again, nothing>
Your identification has been saved in JUNOS_auto_id_rsa.
Your public key has been saved in JUNOS_auto_id_rsa.pub.
3 Once completed, verify that you have two new files in your working directory:
JUNOS_auto_id_rsa Private SSH key, reserved for use by your management automation
application only
JUNOS_auto_id_rsa.pubCorresponding public SSH key (think of it as a certificate) is able to
authenticate the private key
4 Configure a dedicated user profile to be used for NETCONF access that makes use of thepreviously generated key-pair Apply the .pub file contents to the Junos configuration
adamc@router> show configuration system login user auto