async rpc ncclient example

async rpc ncclient example

ncclient is a great Python library that facilitates client-side scripting and application development around the NETCONF protocol:

Typically, one uses the provided functions in synchronous mode, where replies are awaited and the result returned. I was however in need of asynchronous mode, where operations return immediately, allowing me to do ‘other stuff’ and periodically check if a result came in and process it accordingly.

In search of example code using async mode turned out to be harder than I thought. Starting from a synchronous example script that sends a RPC command to retrieve software information and extract the hostname from it (, I ended up with the following working asynchronous version of the same script:

from ncclient import manager
from ncclient.xml_ import *
import time
from ncclient.devices.junos import JunosDeviceHandler

def connect(host, port, user, password):
    conn = manager.connect(host=host,
                           device_params={'name': 'junos'},

    junos_dev_handler = JunosDeviceHandler(
        device_params={'name': 'junos',
                       'local': False})

    conn.async_mode = True

    rpc = new_ele('get-software-information')
    obj = conn.rpc(rpc)

    # for demo purposes, we just wait for the result
    while not obj.event.is_set():
        print('waiting for answer ...')

    result = NCElement(obj.reply,

    print 'Hostname: ', result.findtext('.//host-name')

if __name__ == '__main__':
    connect('pe1', 830, 'lab', 'lab123')

Executed against a device:

$ python
waiting for answer ...
waiting for answer ...
Hostname:  pe1


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blog at

Up ↑

%d bloggers like this: