Contents:
jnpr.junos.cfg.phyport.base.
PhyPortBase
(junos, namevar=None, **kvargs)[source]¶Bases: jnpr.junos.cfg.resource.Resource
[edit interfaces <name>]
PORT_DUPLEX
= {'full': 'full-duplex', 'half': 'half-duplex'}¶PROPERTIES
= ['admin', 'description', 'speed', 'duplex', 'mtu', 'loopback', '$unit_count']¶jnpr.junos.cfg.phyport.switch.
PhyPortSwitch
(junos, namevar=None, **kvargs)[source]¶Bases: jnpr.junos.cfg.phyport.base.PhyPortBase
PORT_SPEED
= {'100m': 'ethernet-100m', '10m': 'ethernet-10m', '1g': 'ethernet-1g', 'auto': 'auto-negotiation'}¶jnpr.junos.cfg.resource.
Resource
(junos, namevar=None, **kvargs)[source]¶Bases: object
D
¶returns the Device object bound to this resource/manager
M
¶returns the :Resource: manager associated to this resource
P
¶returns the parent of the associated Junos object
PROPERTIES
= ['_exists', '_active']¶R
¶returns the Device RPC meta object
__init__
(junos, namevar=None, **kvargs)[source]¶Resource or Resource-Manager constructor. All managed resources and resource-managers inherit from this class.
If not None, identifies a specific resource by ‘name’. The format of the name is resource dependent. Most resources take a single string name, while others use tuples for compound names. refer to each resource for the ‘namevar’ definition
If namevar is None, then the instance is a Resource-Manager (RM). The RM is then used to select specific resources by name using the __getitem__ overload.
activate
()[source]¶activate resource in Junos config the same as the Junos config-mode “activate” command
active
¶is this resource configuration active on the Junos device?
RuntimeError: | if invoked on a manager object |
---|
catalog
¶returns a dictionary of resources
deactivate
()[source]¶activate resource in Junos config the same as the Junos config-mode “deactivate” command
delete
()[source]¶remove configuration from Junos device the same as the Junos config-mode “delete” command
exists
¶does this resource configuration exist on the Junos device?
RuntimError: | if invoked on a manager |
---|
is_mgr
¶is this a resource manager?
is_new
¶is this a new resource? that is, it does not exist on the Junos device when it was initally retrieved
RuntimeError: | if invoked on a manager |
---|
list
¶returns a list of named resources
manages
¶a resource may contain sub-managers for hierarchical oriented resources. this method will return a list of manager names attached to this resource, or :None: if there are not any
name
¶the name of the resource
RuntimeError: | if invoked on a manager |
---|
propcopy
(p_name)[source]¶proptery from :has: to :should:
performs a ‘deepcopy’ of the property; used to make changes to list, dict type properties
rename
(new_name)[source]¶rename resource in Junos configuration the same as the Junos config-mode “rename” command
reorder
(**kvargs)[source]¶move the configuration within the Junos hierarcy the same as the Junos config-mode “insert” command
Kvargs: | after=”<name>” before=”<name>” |
---|
write
(**kvargs)[source]¶write resource configuration stored in :should: back to device
xml
¶for debugging the resource XML configuration that was read from the Junos device
jnpr.junos.cfg.user.
User
(junos, namevar=None, **kvargs)[source]¶Bases: jnpr.junos.cfg.resource.Resource
[edit system login user <name>]
MANAGES
= {'sshkey': <class 'jnpr.junos.cfg.user_ssh_key.UserSSHKey'>}¶PROPERTIES
= ['uid', 'fullname', 'userclass', 'password', '$password', '$sshkeys']¶jnpr.junos.cfg.user_ssh_key.
UserSSHKey
(junos, namevar=None, **kvargs)[source]¶Bases: jnpr.junos.cfg.resource.Resource
[edit system login user <name> authentication <key-type> <key-value> ]
PROPERTIES
= []¶load_key
(path=None, key_value=None)[source]¶Adds a new ssh-key to the user authentication. You can provide either the path to the ssh-key file, or the contents of they key (useful for loading the same key on many devices)
Path: | (optional) path to public ssh-key file on the local server, |
---|---|
Key_value: | (optional) the contents of the ssh public key |
jnpr.junos.factory.cfgtable.
CfgTable
(dev=None, xml=None, path=None, mode=None)[source]¶Bases: jnpr.junos.factory.table.Table
__init__
(dev=None, xml=None, path=None, mode=None)[source]¶Dev: | Device instance |
---|---|
Xml: | lxml Element instance |
Path: | file path to XML, to be used rather than :dev: |
append
()[source]¶It creates lxml nodes with field name as xml tag and its value given by user as text of xml node. The generated xml nodes are appended to configuration xml at appropriate hierarchy.
Warning
xml node that are appended cannot be changed later hence care should be taken to assign correct value to table fields before calling append.
get
(*vargs, **kvargs)[source]¶Retrieve configuration data for this table. By default all child keys of the table are loaded. This behavior can be overridden by with kvargs[‘nameonly’]=True
Parameters: |
|
---|
get_table_xml
()[source]¶It returns lxml object of configuration xml that is generated from table data (field=value) pairs. To get a valid xml this method should be used after append() is called.
keys_required
¶True/False - if this Table requires keys
load
(**kvargs)[source]¶Load configuration xml having table data (field=value) in candidate db. This method should be used after append() is called to get the desired results.
Parameters: |
|
---|---|
Returns: | Class object. |
Raises: |
|
required_keys
¶return a list of the keys required when invoking :get(): and :get_keys():
reset
()[source]¶Initialize fields of set table to it’s default value (if mentioned in Table/View) else set to None.
set
(**kvargs)[source]¶Load configuration data in running db. It performs following operation in sequence.
This method should be used after append() is called to get the desired results.
Parameters: |
|
---|---|
Returns: | Class object: |
Raises: |
|
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.
jnpr.junos.factory.factory_cls.
FactoryOpTable
(cmd, args=None, args_key=None, item=None, key='name', view=None, table_name=None)[source]¶jnpr.junos.factory.factory_cls.
FactoryView
(fields, **kvargs)[source]¶Fields: | dictionary of fields, structure of which is ~internal~ and should not be defined explicitly. use the RunstatMaker.Fields() mechanism to create theserather than hardcoding the dictionary structures; since they might change over time. |
---|---|
Kvargs: | ‘view_name’ to name the class. this could be useful for debug or eventual callback mechanisms. ‘groups’ is a dict of name/xpath assocaited to fields this technique would be used to extract fields from node-set elements like port <if-device-flags>. ‘extends’ names the base View class to extend. using this technique you can add to existing defined Views. |
This file contains the FactoryLoader class that is used to dynamically create Runstat Table and View objects from a <dict> of data. The <dict> can originate from any kind of source: YAML, JSON, program. For examples of YAML refer to the .yml files in this jnpr.junos.op directory.
jnpr.junos.factory.factory_loader.
FactoryLoader
[source]¶Bases: object
Used to load a <dict> of data that contains Table and View definitions.
The primary method is :load(): which will return a <dict> of item-name and item-class definitions.
If you want to import these definitions directly into your namespace, (like a module) you would do the following:
loader = FactoryLoader() catalog = loader.load( <catalog_dict> ) globals().update( catalog )
If you did not want to do this, you can access the items as the catalog. For example, if your <catalog_dict> contained a Table called MyTable, then you could do something like:
MyTable = catalog[‘MyTable’] table = MyTable(dev) table.get() …
jnpr.junos.factory.optable.
OpTable
(dev=None, xml=None, path=None)[source]¶Bases: jnpr.junos.factory.table.Table
get
(*vargs, **kvargs)[source]¶Retrieve the XML table data from the Device instance and returns back the Table instance - for call-chaining purposes.
If the Table was created with a :path: rather than a Device, then this method will load the XML from that file. In this case, the *vargs, and **kvargs are not used.
ALIAS: __call__
Vargs: | [0] is the table :arg_key: value. This is used so that the caller can retrieve just one item from the table without having to know the Junos RPC argument. |
---|---|
Kvargs: | these are the name/value pairs relating to the specific Junos XML command attached to the table. For example, if the RPC is ‘get-route-information’, there are parameters such as ‘table’ and ‘destination’. Any valid RPC argument can be passed to :kvargs: to further filter the results of the :get(): operation. neato! |
jnpr.junos.factory.table.
Table
(dev=None, xml=None, path=None)[source]¶Bases: object
D
¶the Device instance
ITEM_NAME_XPATH
= 'name'¶ITEM_XPATH
= None¶RPC
¶the Device.rpc instance
VIEW
= None¶__init__
(dev=None, xml=None, path=None)[source]¶Dev: | Device instance |
---|---|
Xml: | lxml Element instance |
Path: | file path to XML, to be used rather than :dev: |
hostname
¶is_container
¶True if this table does not have records, but is a container of fields False otherwise
key_list
¶the list of keys, as property for caching
savexml
(path, hostname=False, timestamp=False, append=None)[source]¶Save a copy of the table XML data to a local file. The name of the output file (:path:) can include the name of the Device host, the timestamp of this action, as well as any user-defined appended value. These ‘add-ons’ will be added to the :path: value prior to the file extension in the order (hostname,timestamp,append), separated by underscore (_).
For example, if both hostname=True and append=’BAZ1’, then when :path: = ‘/var/tmp/foo.xml’ and the Device.hostname is “srx123”, the final file-path will be “/var/tmp/foo_srx123_BAZ1.xml”
Path: | file-path to write the XML file on the local filesystem |
---|---|
Hostname: | if True, will append the hostname to the :path: |
Timestamp: |
|
Append: | any <str> value that you’d like appended to the :path: value preceding the filename extension. |
view
¶returns the current view assigned to this table
jnpr.junos.factory.view.
View
(table, view_xml)[source]¶Bases: object
View is the base-class that makes extracting values from XML data appear as objects with attributes.
D
¶return the Device instance for this View
FIELDS
= {}¶GROUPS
= None¶ITEM_NAME_XPATH
= 'name'¶T
¶return the Table instance for the View
__init__
(table, view_xml)[source]¶Table: | instance of the RunstatTable |
---|---|
View_xml: | this should be an lxml etree Elemenet object. This constructor also accepts a list with a single item/XML |
key
¶return the name of view item
name
¶return the name of view item
refresh
()[source]¶~~~ EXPERIMENTAL ~~~ refresh the data from the Junos device. this only works if the table provides an “args_key”, does not update the original table, just this specific view/item
updater
(**kwds)[source]¶provide the ability for subclassing objects to extend the definitions of the fields. this is implemented as a context manager with the form called from the subclass constructor:
- with self.extend() as more:
- more.fields = <dict> more.groups = <dict> # optional
xml
¶returns the XML associated to the item
jnpr.junos.factory.viewfields.
ViewFields
[source]¶Bases: object
Used to dynamically create a field dictionary used with the RunstatView class
astype
(name, xpath=None, astype=<type 'int'>, **kvargs)[source]¶field string value will be passed to function :astype:
This is typically used to do simple type conversions, but also works really well if you set :astype: to a function that does a basic converstion like look at the value and change it to a True/False. For example:
astype=lambda x: True if x == ‘enabled’ else False
end
¶flag
(name, xpath=None, **kvargs)[source]¶field is a flag, results in True/False if the xpath element exists or not. Model this as a boolean type <bool>
jnpr.junos.factory.
loadyaml
(path)[source]¶Load a YAML file at :path: that contains Table and View definitions. Returns a <dict> of item-name anditem-class definition.
If you want to import these definitions directly into your namespace, (like a module) you would do the following:
globals().update( loadyaml( <path-to-yaml-file> ))
If you did not want to do this, you can access the items as the <dict>. For example, if your YAML file contained a Table called MyTable, then you could do something like:
catalog = loadyaml( <path-to-yaml-file> ) MyTable = catalog[‘MyTable’]
table = MyTable(dev) table.get() …
jnpr.junos.factory.
FactoryLoader
[source]¶Bases: object
Used to load a <dict> of data that contains Table and View definitions.
The primary method is :load(): which will return a <dict> of item-name and item-class definitions.
If you want to import these definitions directly into your namespace, (like a module) you would do the following:
loader = FactoryLoader() catalog = loader.load( <catalog_dict> ) globals().update( catalog )
If you did not want to do this, you can access the items as the catalog. For example, if your <catalog_dict> contained a Table called MyTable, then you could do something like:
MyTable = catalog[‘MyTable’] table = MyTable(dev) table.get() …
A dictionary-like object of read-only facts about the Junos device.
These facts are accessed as the facts attribute of a Device object instance. For example, if dev is an instance of a Device object, the hostname of the device can be accessed with:
dev.facts['hostname']
Force a refresh of all facts with:
dev.facts_refresh()
Force a refresh of a single fact with:
dev.facts_refresh(keys='hostname')
Force a refresh of a set of facts with:
dev.facts_refresh(keys=('hostname','domain','fqdn'))
there is a problem gathering the value of a specific fact/key, or if the fact is not supported on a given platform, then the fact/key will have the value None (the None object, not a string.)
Accessing a dictionary key which does not correspond to an available fact will raise a KeyError (the same behavior as accessing a non-existent key of a normal dict.)
The following dictionary keys represent the available facts and their meaning:
2RE: | A boolean indicating if the device has more than one Routing Engine installed. |
---|---|
_iri_hostname: | A dictionary keyed by internal routing instance ip addresses. The value of each key is the internal routing instance hostname for the ip |
_iri_ip: | A dictionary keyed by internal routing instance hostnames. The value of each key is the internal routing instance ip for the hostname |
current_re: | A list of internal routing instance hostnames for the current RE. These hostnames identify things like the RE’s slot (‘re0’ or ‘re1’), the RE’s mastership state (‘master’ or ‘backup’), and node in a VC (‘member0’ or ‘member1’) |
domain: | The domain name configured at the [edit system domain-name] configuration hierarchy. |
fqdn: | The device’s hostname + domain |
HOME: | A string indicating the home directory of the current user. |
hostname: | A string containing the hostname of the current Routing Engine. |
hostname_info: | A dictionary keyed on Routing Engine name. The value of each key is the hostname of the Routing Engine. |
ifd_style: | The type of physical interface (ifd) supported by the device. Choices are ‘CLASSIC’ or ‘SWITCH’. |
junos_info: | A two-level dictionary providing Junos software version information for each RE in the system. The first-level key is the name of the RE. The second level key is ‘text’ for the version as a string and ‘object’ for the version as a version_info object. |
master: | On a single chassis/node system, a string value of ‘RE0’ or ‘RE1’ indicating which RE is master. On a multi-chassis or multi-node system, the value is a list of these strings indicating whether RE0 or RE1 is master. There is one entry in the list for each chassis/node in the system. |
model: | An uppercase string containing the model of the chassis in which the current Routing Engine resides. |
model_info: | A dictionary keyed on Routing Engine name. The value of each key is an uppercase string containing the model of the chassis in which the Routing Engine resides. |
personality: | A string which is generally based on the platform and indicates the behavior of the device. |
RE0: | A dictionary with information about RE0 (if present). The keys of the dictionary are: mastership_state, status, model, up_time, and last_reboot_reason. |
RE1: | A dictionary with information about RE1 (if present). The keys of the dictionary are: mastership_state, status, model, up_time, and last_reboot_reason. |
RE_hw_mi: | (Routing Engine hardware multi-instance) A boolean indicating if this is a multi-chassis system. |
re_info: | A three-level dictionary with information about the Routing Engines in the device. The first-level key is the chassis or node name. The second-level key is the slot number, the third-level keys are: mastership_state, status, model, and last_reboot_reason. A first-level key with a value of ‘default’ will always be present and represents the first chassis/node of the system (Note: the first chasis/node of the system is not necessarily the ‘master’ node in a VC.) A second-level key with a value of ‘default’ will always be present for the default chassis/node and represents the first Routing Engine on the first node/chassis. (Note: the first RE of a chassis/node is not necessarily the ‘master’ RE of the chassis/node. See the RE_master fact for info on the ‘master’ RE of each chassis/node.) |
re_master: | A dictionary indicating which RE slot is master for each chassis/node in the system. The dictionary key is the chassis or node name. A key with a value of ‘default’ will always be present and represents the first node/chassis of the system. (Note: the first chassis/node of the system is not necessarily the ‘master’ node in a VC. See the vc_master fact to determine which chassis/node is the master of a VC.) |
serialnumber: | A string containing the serial number of the device’s chassis. If there is no chassis serial number, the serial number of the backplane or midplane is returned. |
srx_cluster: | A boolean indicating if the device is part of an SRX cluster. |
srx_cluster_id: | A string containing the configured cluster id |
srx_cluster_redundancy_group: | |
A multi-level dictionary of information about the SRX cluster redundancy groups on the device. The first-level key is the redundancy group id. The second-level keys are: cluster_id, failover_count, node0, and node1. The node0 and node1 keys have third-level keys of priority, preempt, status, and failover_mode. The values for this fact correspond to the values of the ‘show chassis cluster status’ CLI command. | |
switch_style: | A string which indicates the Ethernet switching syntax style supported by the device. Possible values are: ‘BRIDGE_DOMAIN’, ‘VLAN’, ‘VLAN_L2NG’, or ‘NONE’. |
vc_capable: | A boolean indicating if the device is currently configured in a virtual chassis. In spite of the name, this fact does NOT indicate whether or not the device is CAPABLE of joining a VC. |
vc_fabric: | A boolean indicating if the device is currently in fabric mode. |
vc_master: | A string indicating the chassis/node which is currently the master of the VC. |
vc_mode: | A string indicating the current virtual chassis mode of the device. |
version: | A string containing the Junos version of the current Routing Engine. |
version_info: | The Junos version of the current Routing Engine as a version_info object. |
version_RE0: | A string containing the Junos version of the RE in slot 0. (Assuming the system contains an RE0.) |
version_RE1: | A string containing the Junos version of the RE in slot 1. (Assuming the system contains an RE1) |
virtual: | A boolean indicating if the device is virtual. |
Pythonifier for ARP Table/View
Pythonifier for BFD Table/View
Pythonifier for EthPort Table/View
Pythonifier for ISIS Table/View
Pythonifier for LACP Table/View
Pythonifier for LDP Table/View
Pythonifier for LLDP Table/View
Pythonifier for PhyPort Table/View
Pythonifier for Route Table/View
Pythonifier for Xcvr Table/View
Pythonifier for AutoSys Table/View
Pythonifier for BGP Table/View
Pythonifier for Static route Table/View
Pythonifier for Syslog Table/View
Pythonifier for User Table/View
jnpr.junos.utils.config.
Config
(dev, mode=None, **kwargs)[source]¶Bases: jnpr.junos.utils.util.Util
Overview of Configuration Utilities.
commit()
: commit changescommit_check()
: perform the commit check operationdiff()
: return the diff string between running and candidate configload()
: load changes into the candidate configlock()
: take an exclusive lock on the candidate configpdiff()
: prints the diff string (debug/helper)rescue()
: controls “rescue configuration”rollback()
: perform the load rollback commandunlock()
: release the exclusive lock__init__
(dev, mode=None, **kwargs)[source]¶Parameters: |
|
---|
# mode can be private/dynamic/exclusive/batch/ephemeral
with Config(dev, mode='exclusive') as cu:
cu.load('set system services netconf traceoptions file xyz',
format='set')
print cu.diff()
cu.commit()
Warning
Ephemeral databases are an advanced Junos feature which if used incorrectly can have serious negative impact on the operation of the Junos device. We recommend you consult JTAC and/or you Juniper account team before deploying the ephemeral database feature in your network.
commit
(**kvargs)[source]¶Commit a configuration.
Parameters: |
|
---|---|
Returns: |
|
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: |
|
---|---|
Raises: |
|
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: |
|
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: |
|
---|---|
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: |
|
---|---|
Returns: |
Note
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.
FS
(dev)[source]¶Bases: jnpr.junos.utils.util.Util
Filesystem (FS) utilities:
cat()
: show the contents of a filechecksum()
: calculate file checksum (md5,sha256,sha1)cp()
: local file copy (not scp)cwd()
: change working directoryls()
: return file/dir listingmkdir()
: create a directorypwd()
: get working directorymv()
: local file renamerm()
: local file deletermdir()
: remove a directorystat()
: return file/dir informationstorage_usage()
: return storage usagedirectory_usage()
: return directory usagestorage_cleanup()
: perform storage storage_cleanupstorage_cleanup_check()
: returns a list of files which will besymlink()
: create a symlinktgz()
: tar+gzip a directorycat
(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: |
|
---|---|
Returns: | checksum value (str) or |
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: |
|
---|
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: |
|
---|---|
Returns: | dict collection of file information or |
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. |
---|
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 |
---|
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: |
|
---|
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.
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: |
|
---|
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: |
|
---|---|
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: |
|
---|---|
Returns: | resulting string of data in a list |
Return type: | list |
Warning
need to add a timeout safeguard
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.
install()
: perform the entire software installation processreboot()
: reboots the system for the new image to take effectpoweroff()
: shutdown the systemput()
: SCP put package file onto Junos devicepkgadd()
: performs the ‘request’ operation to install the packagevalidate()
: performs the ‘request’ to validate the packageinstall
(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, cleanfs_timeout=300, checksum_timeout=300, checksum_algorithm='md5', force_copy=False, all_re=True, vmhost=False, **kwargs)[source]¶Performs the complete installation of the package that includes the following steps:
True
False
True
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: |
|
---|---|
Returns: |
|
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.
local_checksum
(package, algorithm='md5')[source]¶Computes the checksum value on the local package file.
Parameters: |
|
---|---|
Returns: | checksum (str) |
Raises: | IOError – when package file does not exist |
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 |
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 |
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, vmhost=False, **kvargs)[source]¶Issue the RPC equivalent of the ‘request system software add’ command
or the ‘request vmhost software add’ command on the package.
If vhmhost=False, the <request-package-add> RPC is used and the
The “no-validate” options is set. If you want to validate
the image, do that using the specific validate()
method.
If vmhost=True, the <request-vmhost-package-add> RPC is used.
If you want to reboot the device, invoke the reboot()
method
after installing the software rather than passing the reboot=True
parameter.
Parameters: |
|
---|
Warning
Refer to the restrictions listed in install()
.
pkgaddISSU
(remote_package, vmhost=False, **kvargs)[source]¶Issue the RPC equivalent of the ‘request system software in-service-upgrade’ command or the ‘request vmhost software in-service-upgrade’ command on the package. If vhmhost=False, the <request-package-in-service-upgrade> RPC is used. If vmhost=True, the <request-vmhost-package-in-service-upgrade> RPC is used.
Parameters: |
|
---|
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: |
|
Raises: | RpcError – when command is not successful. |
Todo
need to better handle the exception event.
put
(package, remote_path='/var/tmp', progress=None)[source]¶SCP or FTP ‘put’ the package file from the local server to the remote device.
Parameters: |
|
---|
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: |
|
---|---|
Returns: |
|
Raises: | RpcError – when command is not successful. |
Todo
need to better handle the exception event.
remote_checksum
(remote_package, timeout=300, algorithm='md5')[source]¶Computes a checksum of the remote_package file on the remote device.
Parameters: |
|
---|---|
Returns: |
|
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, remote_path='/var/tmp', progress=None, cleanfs=True, cleanfs_timeout=300, checksum=None, checksum_timeout=300, checksum_algorithm='md5', force_copy=False)[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 checksum.
Parameters: |
|
---|---|
Returns: |
|
Junos PyEZ Utility Base Class
FTP utility
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: |
|
---|
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.9/docs')[source]¶This function is used to download file from router to local execution server/shell.
Parameters: |
|
---|---|
Returns: | True if the transfer succeeds, else False |
put
(local_file, remote_path=None)[source]¶This function is used to upload file to the router from local execution server/shell.
Parameters: |
|
---|---|
Returns: | True if the transfer succeeds, else False |
jnpr.junos.device.
Device
(*vargs, **kvargs)[source]¶Bases: jnpr.junos.device._Connection
Junos Device class.
ON_JUNOS
:True
when this code is running on a Junos device,
vs. running on a local-server remotely connecting to a device.auto_probe
:When non-zero the call to open()
will probe for NETCONF
reachability before proceeding with the NETCONF session establishment.
If you want to enable this behavior by default, you could do the
following in your code:
from jnpr.junos import Device
# set all device open to auto-probe with timeout of 10 sec
Device.auto_probe = 10
dev = Device( ... )
dev.open() # this will probe before attempting NETCONF connect
__init__
(*vargs, **kvargs)[source]¶Device object constructor.
Parameters: |
|
---|
connected
¶open
(*vargs, **kvargs)[source]¶Opens a connection to the device using existing login/auth information.
Parameters: |
|
---|---|
Returns Device: | Device instance (self). |
Raises: |
|
transform
¶Returns: | the current RPC XML Transformation. |
---|
jnpr.junos.exception.
CommitError
(rsp, cmd=None, errs=None)[source]¶Bases: jnpr.junos.exception.RpcError
Generated in response to a commit-check or a commit action.
__init__
(rsp, cmd=None, errs=None)[source]¶Cmd: | is the rpc command |
---|---|
Rsp: | is the rpc response (after <rpc-reply>) |
Errs: | is a list of dictionaries of extracted <rpc-error> elements. |
Dev: | is the device rpc was executed on |
Timeout: | is the timeout value of the device |
Re: | is the RE or member exception occured on |
jnpr.junos.exception.
ConfigLoadError
(rsp, cmd=None, errs=None)[source]¶Bases: jnpr.junos.exception.RpcError
Generated in response to a failure when loading a configuration.
__init__
(rsp, cmd=None, errs=None)[source]¶Cmd: | is the rpc command |
---|---|
Rsp: | is the rpc response (after <rpc-reply>) |
Errs: | is a list of dictionaries of extracted <rpc-error> elements. |
Dev: | is the device rpc was executed on |
Timeout: | is the timeout value of the device |
Re: | is the RE or member exception occured on |
jnpr.junos.exception.
ConnectAuthError
(dev, msg=None)[source]¶Bases: jnpr.junos.exception.ConnectError
Generated if the user-name, password is invalid
jnpr.junos.exception.
ConnectClosedError
(dev)[source]¶Bases: jnpr.junos.exception.ConnectError
Generated if connection unexpectedly closed
jnpr.junos.exception.
ConnectError
(dev, msg=None)[source]¶Bases: exceptions.Exception
Parent class for all connection related exceptions
host
¶login host name/ipaddr
msg
¶login SSH port
port
¶login SSH port
user
¶login user-name
jnpr.junos.exception.
ConnectNotMasterError
(dev, msg=None)[source]¶Bases: jnpr.junos.exception.ConnectError
Generated if the connection is made to a non-master routing-engine. This could be a backup RE on an MX device, or a virtual-chassis member (linecard), for example
jnpr.junos.exception.
ConnectRefusedError
(dev, msg=None)[source]¶Bases: jnpr.junos.exception.ConnectError
Generated if the specified host denies the NETCONF; could be that the services is not enabled, or the host has too many connections already.
jnpr.junos.exception.
ConnectTimeoutError
(dev, msg=None)[source]¶Bases: jnpr.junos.exception.ConnectError
Generated if the NETCONF session fails to connect, could be due to the fact the device is not ip reachable; bad ipaddr or just due to routing
jnpr.junos.exception.
ConnectUnknownHostError
(dev, msg=None)[source]¶Bases: jnpr.junos.exception.ConnectError
Generated if the specific hostname does not DNS resolve
jnpr.junos.exception.
FactLoopError
[source]¶Bases: exceptions.RuntimeError
Generated when there is a loop in fact gathering.
jnpr.junos.exception.
JSONLoadError
(exception, rpc_content)[source]¶Bases: exceptions.Exception
Generated if json content of rpc reply fails to load
jnpr.junos.exception.
LockError
(rsp)[source]¶Bases: jnpr.junos.exception.RpcError
Generated in response to attempting to take an exclusive lock on the configuration database.
jnpr.junos.exception.
PermissionError
(rsp, cmd=None, errs=None)[source]¶Bases: jnpr.junos.exception.RpcError
Generated in response to invoking an RPC for which the auth user does not have user-class permissions.
PermissionError.message gives you the specific RPC that cause the exceptions
__init__
(rsp, cmd=None, errs=None)[source]¶Cmd: | is the rpc command |
---|---|
Rsp: | is the rpc response (after <rpc-reply>) |
Errs: | is a list of dictionaries of extracted <rpc-error> elements. |
Dev: | is the device rpc was executed on |
Timeout: | is the timeout value of the device |
Re: | is the RE or member exception occured on |
jnpr.junos.exception.
ProbeError
(dev, msg=None)[source]¶Bases: jnpr.junos.exception.ConnectError
Generated if auto_probe is enabled and the probe action fails
jnpr.junos.exception.
RpcError
(cmd=None, rsp=None, errs=None, dev=None, timeout=None, re=None)[source]¶Bases: exceptions.Exception
Parent class for all junos-pyez RPC Exceptions
__init__
(cmd=None, rsp=None, errs=None, dev=None, timeout=None, re=None)[source]¶Cmd: | is the rpc command |
---|---|
Rsp: | is the rpc response (after <rpc-reply>) |
Errs: | is a list of dictionaries of extracted <rpc-error> elements. |
Dev: | is the device rpc was executed on |
Timeout: | is the timeout value of the device |
Re: | is the RE or member exception occured on |
jnpr.junos.exception.
RpcTimeoutError
(dev, cmd, timeout)[source]¶Bases: jnpr.junos.exception.RpcError
Generated in response to a RPC execution timeout.
jnpr.junos.exception.
SwRollbackError
(rsp, re=None)[source]¶Bases: jnpr.junos.exception.RpcError
Generated in response to a SW rollback error.
jnpr.junos.exception.
UnlockError
(rsp)[source]¶Bases: jnpr.junos.exception.RpcError
Generated in response to attempting to unlock the configuration database.
jnpr.junos.rpcmeta.
_RpcMetaExec
(junos)[source]¶Bases: object
__init__
(junos)[source]¶~PRIVATE CLASS~ creates an RPC meta-executor object bound to the provided ez-netconf :junos: object
get
(filter_select=None, ignore_warning=False, **kwargs)[source]¶Retrieve running configuration and device state information using <get> rpc
dev.rpc.get()
dev.rpc.get(ignore_warning=True)
dev.rpc.get(filter_select='bgp') or dev.rpc.get('bgp')
dev.rpc.get(filter_select='bgp/neighbors')
dev.rpc.get("/bgp/neighbors/neighbor[neighbor-address='10.10.0.1']"
"/timers/state/hold-time")
dev.rpc.get('mpls', ignore_warning=True)
Parameters: |
|
---|---|
Returns: | xml object |
get_config
(filter_xml=None, options={}, model=None, namespace=None, remove_ns=True, **kwargs)[source]¶retrieve configuration from the Junos device
dev.rpc.get_config()
dev.rpc.get_config(filter_xml='<system><services/></system>')
dev.rpc.get_config(filter_xml='system/services')
dev.rpc.get_config(
filter_xml=etree.XML('<system><services/></system>'),
options={'format': 'json'})
# to fetch junos as well as yang model configs
dev.rpc.get_config(model=True)
# openconfig yang example
dev.rpc.get_config(filter_xml='bgp', model='openconfig')
dev.rpc.get_config(filter_xml='<bgp><neighbors></neighbors></bgp>',
model='openconfig')
# custom yang example
dev.rpc.get_config(filter_xml='l2vpn', model='custom',
namespace="http://yang.juniper.net/customyang/l2vpn")
# ietf yang example
dev.rpc.get_config(filter_xml='interfaces', model='ietf')
# ietf-softwire yang example
dev.rpc.get_config(filter_xml='softwire-config', model='ietf',
namespace="urn:ietf:params:xml:ns:yang:ietf-softwire",
options={'format': 'json'})
Filter_xml: | fully XML formatted tag which defines what to retrieve, when omitted the entire configuration is returned; the following returns the device host-name configured with “set system host-name” |
---|
config = dev.rpc.get_config(filter_xml=etree.XML('''
<configuration>
<system>
<host-name/>
</system>
</configuration>'''))
Options: | is a dictionary of XML attributes to set within the <get-configuration> RPC; the following returns the device host-name either configured with “set system host-name” and if unconfigured, the value inherited from apply-group re0|re1, typical for multi-RE systems |
---|
config = dev.rpc.get_config(filter_xml=etree.XML('''
<configuration>
<system>
<host-name/>
</system>
</configuration>'''),
options={'database':'committed','inherit':'inherit'})
Parameters: |
|
---|
dev.rpc.get_config(filter_xml='bgp', model='openconfig',
remove_ns=False)
load_config
(contents, ignore_warning=False, **options)[source]¶loads :contents: onto the Junos device, does not commit the change.
Parameters: | 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: dev.rpc.load_config(cnf, ignore_warning=True)
dev.rpc.load_config(cnf,
ignore_warning='vrrp subsystem not running')
dev.rpc.load_config(cnf,
ignore_warning=['vrrp subsystem not running',
'statement not found'])
dev.rpc.load_config(cnf, ignore_warning='statement not found')
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. |
---|---|
Options: | is a dictionary of XML attributes to set within the <load-configuration> RPC. |
The :contents: are interpreted by the :options: as follows:
url=’path’, then :contents: is a None
<otherwise> :contents: is XML structure