We will use a pretty straightforward example to execute show version. We will name this file junos_netconf_1.py:
#!/usr/bin/env python3
from ncclient import manager
conn = manager.connect(
host='192.168.24.252',
port='830',
username='netconf',
password='juniper!',
timeout=10,
device_params={'name':'junos'},
hostkey_verify=False)
result = conn.command('show version', format='text')
print(result)
conn.close_session()
All the fields in the script should be pretty self explanatory with the exception of device_params. Starting from ncclient 0.4.1, the device handler was added to specify different vendors or platforms, for example, the name can be juniper, CSR, Nexus, or Huawei. We also added hostkey_verify=False because we are using a self-signed certificate from the Juniper device.
The returned output is an rpc-reply encoded in XML with and output element:
<rpc-reply message-id="urn:uuid:7d9280eb-1384-45fe-be48-
b7cd14ccf2b7">
<output>
Hostname: foo
Model: olive
JUNOS Base OS boot [12.1R1.9]
JUNOS Base OS Software Suite [12.1R1.9]
<omitted>
JUNOS Runtime Software Suite [12.1R1.9]
JUNOS Routing Software Suite [12.1R1.9]
</output>
</rpc-reply>
We can parse the XML output to just include the output text:
print(result.xpath('output')[0].text)
In junos_netconf_2.py, we will make configuration changes to the device. We will start with some new imports for constructing new XML elements and the connection manager object:
#!/usr/bin/env python3
from ncclient import manager
from ncclient.xml_ import new_ele, sub_ele
conn = manager.connect(host='192.168.24.252', port='830',
username='netconf' , password='juniper!', timeout=10,
device_params={'name':'junos'}, hostkey_v erify=False)
We will lock the configuration and make configuration changes:
# lock configuration and make configuration changes
conn.lock()
# build configuration
config = new_ele('system')
sub_ele(config, 'host-name').text = 'master'
sub_ele(config, 'domain-name').text = 'python'
You can see from the XML display that the node structure with 'system' is the parent of 'host-name' and 'domain-name':
<system>
<host-name>foo</host-name>
<domain-name>bar</domain-name>
...
</system>
We can then push the configuration and commit the configuration. These are normal best practice steps for Juniper configuration changes:
# send, validate, and commit config
conn.load_configuration(config=config)
conn.validate()
commit_config = conn.commit()
print(commit_config.tostring)
# unlock config
conn.unlock()
# close session
conn.close_session()
Overall, the NETCONF steps map pretty well to what you would have done in the CLI steps. Please take a look at the junos_netconf_3.py script for a combination of the previous examples and the functional example.