jnpr.junos.utils

jnpr.junos.utils.config

class jnpr.junos.utils.config.Config(dev, mode=None)[source]

Bases: jnpr.junos.utils.util.Util

Overivew of Configuration Utilities:

  • commit(): commit changes
  • commit_check(): perform the commit check operation
  • diff(): return the diff string between running and candidate config
  • load(): load changes into the candidate config
  • lock(): take an exclusive lock on the candidate config
  • pdiff(): prints the diff string (debug/helper)
  • rescue(): controls “rescue configuration”
  • rollback(): perform the load rollback command
  • unlock(): release the exclusive lock
__init__(dev, mode=None)[source]
Parameters:mode (str) –
Can be used only when creating Config object using
context manager
  • “private” - Work in private database
  • “dynamic” - Work in dynamic database
  • “batch” - Work in batch database
  • “exclusive” - Work with Locking the candidate configuration
# mode can be private/dynamic/exclusive/batch
with Config(dev, mode='exclusive') as cu:
    cu.load('set system services netconf traceoptions file xyz',
            format='set')
    print cu.diff()
    cu.commit()
commit(**kvargs)[source]

Commit a configuration.

Parameters:
  • comment (str) – If provided logs this comment with the commit.
  • confirm (int) – If provided activates confirm safeguard with provided value as timeout (minutes).
  • timeout (int) – If provided the command will wait for completion using the provided value as timeout (seconds). By default the device timeout is used.
  • sync (bool) – On dual control plane systems, requests that the candidate configuration on one control plane be copied to the other control plane, checked for correct syntax, and committed on both Routing Engines.
  • force_sync (bool) – On dual control plane systems, forces the candidate configuration on one control plane to be copied to the other control plane.
  • full (bool) – When true requires all the daemons to check and evaluate the new configuration.
  • detail (bool) – When true return commit detail as XML
  • ignore_warning

    A boolean, string or list of string. If the value is True, it will ignore all warnings regardless of the warning message. If the value is a string, it will ignore warning(s) if the message of each warning matches the string. If the value is a list of strings, ignore warning(s) if the message of each warning matches at least one of the strings in the list.

    For example::
    cu.commit(ignore_warning=True) cu.commit(ignore_warning=’Advertisement-interval is ‘
    ‘less than four times’)
    cu.commit(ignore_warning=[‘Advertisement-interval is ‘
    ‘less than four times’, ‘Chassis configuration for network ‘ ‘services has been changed.’])

    Note

    When the value of ignore_warning is a string, or list of strings, the string is actually used as a case-insensitive regular expression pattern. If the string contains only alpha-numeric characters, as shown in the above examples, this results in a case-insensitive substring match. However, any regular expression pattern supported by the re library may be used for more complicated match conditions.

Returns:

  • True when successful
  • Commit detail XML (when detail is True)

Raises:

CommitError – When errors detected in candidate configuration. You can use the Exception errs variable to identify the specific problems

Warning

If the function does not receive a reply prior to the timeout a RpcTimeoutError will be raised. It is possible the commit was successful. Manual verification may be required.

commit_check()[source]

Perform a commit check. If the commit check passes, this function will return True. If the commit-check results in warnings, they are reported and available in the Exception errs.

Returns:

True if commit-check is successful (no errors)

Raises:
  • CommitError – When errors detected in candidate configuration. You can use the Exception errs variable to identify the specific problems
  • RpcError – When underlying ncclient has an error
diff(rb_id=0)[source]

Retrieve a diff (patch-format) report of the candidate config against either the current active config, or a different rollback.

Parameters:rb_id (int) – rollback id [0..49]
Returns:
  • None if there is no difference
  • ascii-text (str) if there is a difference
load(*vargs, **kvargs)[source]

Loads changes into the candidate configuration. Changes can be in the form of strings (text,set,xml, json), XML objects, and files. Files can be either static snippets of configuration or Jinja2 templates. When using Jinja2 Templates, this method will render variables into the templates and then load the resulting change; i.e. “template building”.

Parameters:
  • vargs[0] (object) – The content to load. If the contents is a string, the framework will attempt to automatically determine the format. If it is unable to determine the format then you must specify the format parameter. If the content is an XML object, then this method assumes you’ve structured it correctly; and if not an Exception will be raised.
  • path (str) –

    Path to file of configuration on the local server. The path extension will be used to determine the format of the contents:

    • “conf”,”text”,”txt” is curly-text-style
    • “set” - ascii-text, set-style
    • “xml” - ascii-text, XML
    • “json” - ascii-text, json

    Note

    The format can specifically set using format.

  • format (str) – Determines the format of the contents. Refer to options from the path description.
  • overwrite (bool) –

    Determines if the contents completely replace the existing configuration. Default is False.

    Note

    This option cannot be used if format is “set”.

  • merge (bool) – If set to True will set the load-config action to merge. the default load-config action is ‘replace’
  • update (bool) –

    If set to True Compare a complete loaded configuration against the candidate configuration. For each hierarchy level or configuration object that is different in the two configurations, the version in the loaded configuration replaces the version in the candidate configuration. When the configuration is later committed, only system processes that are affected by the changed configuration elements parse the new configuration.

    Note

    This option cannot be used if format is “set”.

  • template_path (str) –

    Similar to the path parameter, but this indicates that the file contents are Jinja2 format and will require template-rendering.

    Note

    This parameter is used in conjunction with template_vars. The template filename extension will be used to determine the format-style of the contents, or you can override using format.

  • template (jinja2.Template) – A Jinja2 Template object. Same description as template_path, except this option you provide the actual Template, rather than a path to the template file.
  • template_vars (dict) – Used in conjunction with the other template options. This parameter contains a dictionary of variables to render into the template.
  • ignore_warning

    A boolean, string or list of string. If the value is True, it will ignore all warnings regardless of the warning message. If the value is a string, it will ignore warning(s) if the message of each warning matches the string. If the value is a list of strings, ignore warning(s) if the message of each warning matches at least one of the strings in the list.

    For example::
    cu.load(cnf, ignore_warning=True) cu.load(cnf, ignore_warning=’statement not found’) cu.load(cnf, ignore_warning=[‘statement not found’,
    ‘statement has no contents; ignored’)

    Note

    When the value of ignore_warning is a string, or list of strings, the string is actually used as a case-insensitive regular expression pattern. If the string contains only alpha-numeric characters, as shown in the above examples, this results in a case-insensitive substring match. However, any regular expression pattern supported by the re library may be used for more complicated match conditions.

Returns:

RPC-reply as XML object.

Raises:

ConfigLoadError: When errors detected while loading candidate configuration. You can use the Exception errs variable to identify the specific problems.

lock()[source]

Attempts an exclusive lock on the candidate configuration. This is a non-blocking call.

Returns:True always when successful
Raises:LockError – When the lock cannot be obtained
pdiff(rb_id=0)[source]

Helper method that calls print on the diff (patch-format) between the current candidate and the provided rollback.

Parameters:rb_id (int) – the rollback id value [0-49]
Returns:None
rescue(action, format='text')[source]

Perform action on the “rescue configuration”.

Parameters:
  • action (str) –

    identifies the action as follows:

    • “get” - retrieves/returns the rescue configuration via format
    • “save” - saves current configuration as rescue
    • “delete” - removes the rescue configuration
    • “reload” - loads the rescue config as candidate (no-commit)
  • format (str) –
    identifies the return format when action is
    “get”:
    • “text” (default) - ascii-text format
    • “xml” - as XML object
Returns:

  • When action is ‘get’, then the contents of the rescue configuration is returned in the specified format. If there is no rescue configuration saved, then the return value is None.
  • True when action is “save”.
  • True when action is “delete”.

Note

True regardless if a rescue configuration exists.

  • When action is ‘reload’, return is True if a rescue configuration exists, and False otherwise.

Note

The rescue configuration is only loaded as the candidate, and not committed. You must commit to make the rescue configuration active.

Raises:

ValueError – If action is not one of the above

rollback(rb_id=0)[source]

Rollback the candidate config to either the last active or a specific rollback number.

Parameters:rb_id (int) – The rollback id value [0-49], defaults to 0.
Returns:True always when successful
Raises:ValueError – When invalid rollback id is given
unlock()[source]

Unlocks the candidate configuration.

Returns:True always when successful
Raises:UnlockError – If you attempt to unlock a configuration when you do not own the lock

jnpr.junos.utils.fs

class jnpr.junos.utils.fs.FS(dev)[source]

Bases: jnpr.junos.utils.util.Util

Filesystem (FS) utilities:

cat(path)[source]

Returns the contents of the file path.

Parameters:path (str) – File-path
Returns:contents of the file (str) or None if file does not exist
checksum(path, calc='md5')[source]

Performs the checksum command on the given file path using the required calculation method and returns the string value. If the path is not found on the device, then None is returned.

Parameters:
  • path (str) – file-path on local device
  • calc (str) –

    checksum calculation method:

    • “md5”
    • “sha256”
    • “sha1”
Returns:

checksum value (str) or None if file not found

cp(from_path, to_path)[source]

Perform a local file copy where from_path and to_path can be any valid Junos path argument. Refer to the Junos “file copy” command documentation for details.

Parameters:
  • from_path (str) – source file-path
  • to_path (str) – destination file-path
Returns:True if OK, False if file does not exist.
cwd(path)[source]

Change working directory to path.

Parameters:path (str) – path to working directory
directory_usage(path='.', depth=0)[source]

Returns the directory usage, similar to the unix “du” command.

Returns:dict of directory usage, including subdirectories if depth > 0
ls(path='.', brief=False, followlink=True)[source]

File listing, returns a dict of file information. If the path is a symlink, then by default followlink will recursively call this method to obtain the symlink specific information.

Parameters:
  • path (str) – file-path on local device. defaults to current working directory
  • brief (bool) – when True brief amount of data
  • followlink (bool) – when True (default) this method will recursively follow the directory symlinks to gather data
Returns:

dict collection of file information or None if path is not found

mkdir(path)[source]

Executes the ‘mkdir -p’ command on path.

Warning

REQUIRES SHELL PRIVILEGES

Returns:True if OK, error-message (str) otherwise
mv(from_path, to_path)[source]

Perform a local file rename function, same as “file rename” Junos CLI.

Returns:True if OK, False if file does not exist.
pwd()[source]
Returns:The current working directory path (str)
rm(path)[source]

Performs a local file delete action, per Junos CLI command “file delete”.

Returns:True when successful, False otherwise.
rmdir(path)[source]

Executes the ‘rmdir’ command on path.

Warning

REQUIRES SHELL PRIVILEGES

Parameters:path (str) – file-path to directory
Returns:True if OK, error-message (str) otherwise
stat(path)[source]

Returns a dictionary of status information on the path, or None if the path does not exist.

Parameters:path (str) – file-path on local device
Returns:status information on the file
Return type:dict
storage_cleanup()[source]

Perform the ‘request system storage cleanup’ command to remove files from the filesystem. Return a dict of file name/info on the files that were removed.

Returns:dict on files that were removed
storage_cleanup_check()[source]

Perform the ‘request system storage cleanup dry-run’ command to return a dict of files/info that would be removed if the cleanup command was executed.

Returns:dict of files that would be removed (dry-run)
storage_usage()[source]

Returns the storage usage, similar to the unix “df” command.

Returns:dict of storage usage

Executes the ‘ln -sf from_path to_path‘ command.

Warning

REQUIRES SHELL PRIVILEGES

Returns:True if OK, or error-message (str) otherwise
tgz(from_path, tgz_path)[source]

Create a file called tgz_path that is the tar-gzip of the given directory specified from_path.

Parameters:
  • from_path (str) – file-path to directory of files
  • tgz_path (str) – file-path name of tgz file to create
Returns:

True if OK, error-msg (str) otherwise

jnpr.junos.utils.scp

class jnpr.junos.utils.scp.SCP(junos, **scpargs)[source]

Bases: object

The SCP utility is used to conjunction with jnpr.junos.utils.sw.SW when transferring the Junos image to the device. The SCP can be used for other secure-copy use-cases as well; it is implemented to support the python context-manager pattern. For example:

from jnpr.junos.utils.scp import SCP

with SCP(dev, progress=True) as scp:
    scp.put(package, remote_path)
__init__(junos, **scpargs)[source]

Constructor that wraps paramiko and scp objects.

Parameters:
  • junos (Device) – the Device object
  • scpargs (kvargs) – any additional args to be passed to paramiko SCP
close()[source]

Closes the ssh/scp connection to the device

open(**scpargs)[source]

Creates an instance of the scp object and return to caller for use.

Note

This method uses the same username/password authentication credentials as used by jnpr.junos.device.Device. It can also use ssh_private_key_file option if provided to the jnpr.junos.device.Device

Returns:SCPClient object

jnpr.junos.utils.start_shell

class jnpr.junos.utils.start_shell.StartShell(nc, timeout=30)[source]

Bases: object

Junos shell execution utility. This utility is written to support the “context manager” design pattern. For example:

def _ssh_exec(self, command):
    with StartShell(self._dev) as sh:
        got = sh.run(command)
    return got
__init__(nc, timeout=30)[source]

Utility Constructor

Parameters:
  • nc (Device) – The Device object
  • timeout (int) – Timeout value in seconds to wait for expected string/pattern.
close()[source]

Close the SSH client channel

open()[source]

Open an ssh-client connection and issue the ‘start shell’ command to drop into the Junos shell (csh). This process opens a paramiko.SSHClient instance.

run(command, this='(%|#)\\s', timeout=0)[source]

Run a shell command and wait for the response. The return is a tuple. The first item is True/False if exit-code is 0. The second item is the output of the command.

Parameters:
  • command (str) – the shell command to execute
  • this (str) – the expected shell-prompt to wait for. If this is set to None, function will wait for all the output on the shell till timeout value.
  • timeout (int) – Timeout value in seconds to wait for expected string/pattern (this). If not specified defaults to self.timeout. This timeout is specific to individual run call. If this is provided with None value, function will wait till timeout value to grab all the content from command output.
Returns:

(last_ok, result of the executed shell command (str) )

with StartShell(dev) as ss:
    print ss.run('cprod -A fpc0 -c "show version"', timeout=10)

Note

as a side-effect this method will set the self.last_ok property. This property is set to True if $? is “0”; indicating the last shell command was successful else False. If this is set to None, last_ok will be set to True if there is any content in result of the executed shell command.

send(data)[source]

Send the command data followed by a newline character.

Parameters:data (str) – the data to write out onto the shell.
Returns:result of SSH channel send
wait_for(this='(%|#)\\s', timeout=0)[source]

Wait for the result of the command, expecting this prompt.

Parameters:
  • this (str) – expected string/pattern.
  • timeout (int) – Timeout value in seconds to wait for expected string/pattern. If not specified defaults to self.timeout.
Returns:

resulting string of data in a list

Return type:

list

Warning

need to add a timeout safeguard

jnpr.junos.utils.sw

class jnpr.junos.utils.sw.SW(dev)[source]

Bases: jnpr.junos.utils.util.Util

Software Utility class, used to perform a software upgrade and associated functions. These methods have been tested on simple deployments. Refer to install for restricted use-cases for software upgrades.

Primary methods:
  • install(): perform the entire software installation process
  • reboot(): reboots the system for the new image to take effect
  • poweroff(): shutdown the system
Helpers: (Useful as standalone as well)
  • put(): SCP put package file onto Junos device
  • pkgadd(): performs the ‘request’ operation to install the package
  • validate(): performs the ‘request’ to validate the package
Miscellaneous:
  • rollback: same as ‘request software rollback’
  • inventory: (property) provides file info for current and rollback images on the device
__init__(dev)[source]
install(package=None, pkg_set=None, remote_path='/var/tmp', progress=None, validate=False, checksum=None, cleanfs=True, no_copy=False, issu=False, nssu=False, timeout=1800, **kwargs)[source]

Performs the complete installation of the package that includes the following steps:

  1. computes the local MD5 checksum if not provided in :checksum:
  2. performs a storage cleanup if :cleanfs: is True
  3. SCP copies the package to the :remote_path: directory
  4. computes remote MD5 checksum and matches it to the local value
  5. validates the package if :validate: is True
  6. installs the package

Warning

This process has been validated on the following deployments.

Tested:

  • Single RE devices (EX, QFX, MX, SRX).
  • MX dual-RE
  • EX virtual-chassis when all same HW model
  • QFX virtual-chassis when all same HW model
  • QFX/EX mixed virtual-chassis
  • Mixed mode VC

Known Restrictions:

  • SRX cluster
  • MX virtual-chassis

You can get a progress report on this process by providing a progress callback.

Note

You will need to invoke the reboot() method explicitly to reboot the device.

Parameters:
  • package (str) – The file-path to the install package tarball on the local filesystem
  • pkg_set (list) – The file-paths as list/tuple of the install package tarballs on the local filesystem which will be installed on mixed VC setup.
  • remote_path (str) – The directory on the Junos device where the package file will be SCP’d to or where the package is stored on the device; the default is /var/tmp.
  • validate (bool) – When True this method will perform a config validation against the new image
  • checksum (str) – MD5 hexdigest of the package file. If this is not provided, then this method will perform the calculation. If you are planning on using the same image for multiple updates, you should consider using the local_md5() method to pre calculate this value and then provide to this method.
  • cleanfs (bool) – When True will perform a ‘storeage cleanup’ before SCP’ing the file to the device. Default is True.
  • progress (func) –

    If provided, this is a callback function with a function prototype given the Device instance and the report string:

    def myprogress(dev, report):
      print "host: %s, report: %s" % (dev.hostname, report)
    

    If set to True, it uses sw.progress() for basic reporting by default.

  • no_copy (bool) – When True the software package will not be SCP’d to the device. Default is False.
  • timeout (int) – The amount of time (seconds) before declaring an RPC timeout. This argument was added since most of the time the “package add” RPC takes a significant amount of time. The default RPC timeout is generally around 30 seconds. So this :timeout: value will be used in the context of the SW installation process. Defaults to 30 minutes (30*60=1800)
  • force_host (bool) – (Optional) Force the addition of host software package or bundle (ignore warnings) on the QFX5100 device.
  • issu (bool) – (Optional) When True allows unified in-service software upgrade (ISSU) feature enables you to upgrade between two different Junos OS releases with no disruption on the control plane and with minimal disruption of traffic.
  • nssu (bool) – (Optional) When True allows nonstop software upgrade (NSSU) enables you to upgrade the software running on a Juniper Networks EX Series Virtual Chassis or a Juniper Networks EX Series Ethernet Switch with redundant Routing Engines with a single command and minimal disruption to network traffic.
Returns:

  • True when the installation is successful
  • False otherwise

inventory

Returns dictionary of file listing information for current and rollback Junos install packages. This information comes from the /packages directory.

Warning

Experimental method; may not work on all platforms. If you find this not working, please report issue.

classmethod local_md5(package)[source]

Computes the MD5 checksum value on the local package file.

Parameters:package (str) – File-path to the package (*.tgz) file on the local server
Returns:MD5 checksum (str)
Raises:IOError – when package file does not exist
classmethod local_sha1(package)[source]

Computes the SHA1 checksum value on the local package file.

Parameters:package (str) – File-path to the package (*.tgz) file on the local server
Returns:SHA1 checksum (str)
Raises:IOError – when package file does not exist
classmethod local_sha256(package)[source]

Computes the SHA-256 value on the package file.

Parameters:package (str) – File-path to the package (*.tgz) file on the local server
Returns:SHA-256 checksum (str)
Raises:IOError – when package file does not exist
pkgadd(remote_package, **kvargs)[source]

Issue the ‘request system software add’ command on the package. The “no-validate” options is set by default. If you want to validate the image, do that using the specific validate() method. Also, if you want to reboot the device, suggest using the reboot() method rather reboot=True.

Parameters:
  • remote_package (str) – The file-path to the install package on the remote (Junos) device.
  • kvargs (dict) – Any additional parameters to the ‘request’ command can be passed within kvargs, following the RPC syntax methodology (dash-2-underscore,etc.)

Warning

Refer to the restrictions listed in install().

pkgaddISSU(remote_package, **kvargs)[source]

Issue the ‘request system software nonstop-upgrade’ command on the package.

Parameters:remote_package (str) – The file-path to the install package on the remote (Junos) device.
pkgaddNSSU(remote_package, **kvargs)[source]

Issue the ‘request system software nonstop-upgrade’ command on the package.

Parameters:remote_package (str) – The file-path to the install package on the remote (Junos) device.
poweroff(in_min=0)[source]

Perform a system shutdown, with optional delay (in minutes) .

If the device is equipped with dual-RE, then both RE will be rebooted. This code also handles EX/QFX VC.

Parameters:in_min (int) – time (minutes) before rebooting the device.
Returns:
  • reboot message (string) if command successful
Raises:RpcError – when command is not successful.

Todo

need to better handle the exception event.

classmethod progress(dev, report)[source]

simple progress report function

put(package, remote_path='/var/tmp', progress=None)[source]

SCP ‘put’ the package file from the local server to the remote device.

Parameters:
  • package (str) – File path to the package file on the local file system
  • remote_path (str) – The directory on the device where the package will be copied to.
  • progress (func) – Callback function to indicate progress. If set to True uses scp._scp_progress() for basic reporting by default. See that class method for details.
reboot(in_min=0, at=None, all_re=True)[source]

Perform a system reboot, with optional delay (in minutes) or at a specified date and time.

If the device is equipped with dual-RE, then both RE will be rebooted. This code also handles EX/QFX VC.

Parameters:
  • in_min (int) – time (minutes) before rebooting the device.
  • at (str) – date and time the reboot should take place. The string must match the junos cli reboot syntax
  • all_re (bool) – In case of dual re or VC setup, function by default will reboot all. If all is False will only reboot connected device
Returns:

  • reboot message (string) if command successful

Raises:

RpcError – when command is not successful.

Todo

need to better handle the exception event.

remote_checksum(remote_package, timeout=300)[source]

Computes the MD5 checksum on the remote device.

Parameters:
  • remote_package (str) – The file-path on the remote Junos device
  • timeout (int) – The amount of time (seconds) before declaring an RPC timeout. The default RPC timeout is generally around 30 seconds. So this :timeout: value will be used in the context of the checksum process. Defaults to 5 minutes (5*60=300)
Returns:

  • The MD5 checksum string
  • False when the remote_package is not found.

Raises:

RpcError – RPC errors other than remote_package not found.

rollback()[source]

Issues the ‘request’ command to do the rollback and returns the string output of the results.

Returns:Rollback results (str)
safe_copy(package, **kvargs)[source]

Copy the install package safely to the remote device. By default this means to clean the filesystem to make space, perform the secure-copy, and then verify the MD5 checksum.

Parameters:
  • package (str) – file-path to package on local filesystem
  • remote_path (str) – file-path to directory on remote device
  • progress (func) – call-back function for progress updates. If set to True uses sw.progress() for basic reporting by default.
  • cleanfs (bool) – When True (default) this method will perform the “storage cleanup” on the device.
  • checksum (str) – This is the checksum string as computed on the local system. This value will be used to compare the checksum on the remote Junos device.
Returns:

  • True when the copy was successful
  • False otherwise

validate(remote_package, issu=False, nssu=False, **kwargs)[source]

Issues the ‘request’ operation to validate the package against the config.

Returns:
  • True if validation passes. i.e return code (rc) value is 0
    • False otherwise

jnpr.junos.utils.util

Junos PyEZ Utility Base Class

class jnpr.junos.utils.util.Util(dev)[source]

Bases: object

Base class for all utility classes

__init__(dev)[source]
dev
Returns:the Device object
rpc
Returns:Device RPC meta object

jnpr.junos.utils.ftp

FTP utility

class jnpr.junos.utils.ftp.FTP(junos, **ftpargs)[source]

Bases: ftplib.FTP

FTP utility can be used to transfer files to and from device.

__init__(junos, **ftpargs)[source]
Parameters:
  • junos (Device) – Device object
  • ftpargs (kvargs) – any additional args to be passed to ftplib FTP

Supports python context-manager pattern. For example:

from jnpr.junos.utils.ftp import FTP
with FTP(dev) as ftp:
    ftp.put(package, remote_path)
get(remote_file, local_path='/home/docs/checkouts/readthedocs.org/user_builds/junos-pyez/checkouts/2.1.1/docs')[source]

This function is used to download file from router to local execution server/shell.

Parameters:
  • local_path – path in which to receive files locally
  • remote_file – Full path along with filename on the router. If ignored FILE will be copied to “tmp”
Returns:

True if the transfer succeeds, else False

open()[source]
put(local_file, remote_path=None)[source]

This function is used to upload file to the router from local execution server/shell.

Parameters:
  • local_file – Full path along with filename which has to be copied to router
  • remote_path – path in which to receive the files on the remote host. If ignored FILE will be copied to “tmp”
Returns:

True if the transfer succeeds, else False