Blog Viewer

Scripting How-To: Connect to devices remotely

By Erdem posted 08-05-2015 19:22


Connect to Devices Remotely


Each managed Junos OS device is modeled as a jnpr.junos.Device variable (aka "instance"). The general process is you create a variable for each device, providing at least the hostname. You can optionally provide a username (the default is $USER) and a password (the default is using ssh-keys).
You then open a connection to the device, perform automation activities on it, and finally close the connection.Each managed Junos OS instance maintains a collection of "facts". These facts are loaded when you open a connection to the device. Facts are generally static pieces of information, such as the software version or serial number. These facts form the basis for other modules when creating abstractions.
For example, configuring VLANs on one Junos OS product family might actually be different from another at the XML API level. The purpose of Junos PyEZ is to abstract those differences so the user has a consistent automation interface.


To remotely access a Junos OS device (physical or virtual), you must import the Device type:


1 from jnpr.junos import Device


You can obtain help from the Python shell using: help(Device).


Opening a Connection


To create a Device variable, you must provide at least the target hostname. You can optionally provide the username; if omitted, this will default to the $USER environment value. You can optionally provide a password; if omitted, this will assume that ssh-keys are active. The following code illustrates three ways to access the same device:


1 from jnpr.junos import Device
2 dev = Device('jnpr-dc-fw')                         
3 dev = Device('jnpr-dc-fw', user='jeremy')          
4 dev = Device('jnpr-dc-fw', user='jeremy', password='logmein')


Once you've created the Device, you then open a connection:




If an error occurs in the process, an Exception is raised.


You can call-chain the Device create and connection open together:


1 dev = Device('jnpr-dc-fw').open()



Changing the RPC Timeout


The default timeout for an RPC to transaction is 30 seconds. You might need to change this value for long running requests. Specifically, if you perform a software upgrade you MUST change this value. You can read or write the timeout value as a Device property:


1 # read the value
2 >>> dev.timeout
3 30
4 # change the value to 10 minutes
5 >>> dev.timeout = 10*60



Closing a Device Connection


You should explicitly close the Device connection when you are finished.