| 1 |
import logging |
| 2 |
import sys |
| 3 |
|
| 4 |
from ncclient import manager |
| 5 |
|
| 6 |
# Global constants |
| 7 |
DEVICE_HOST = 'localhost' |
| 8 |
DEVICE_PORT = 830 |
| 9 |
DEVICE_USER = 'admin' |
| 10 |
DEVICE_PASS = 'admin' |
| 11 |
|
| 12 |
EDIT_CONFIG_PAYLOAD = """ |
| 13 |
<config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:alu="urn:ietf:params:xml:ns:netconf:base:1.0"> |
| 14 |
<configure xmlns="urn:nokia.com:sros:ns:yang:sr:conf"> |
| 15 |
<system> |
| 16 |
<security> |
| 17 |
<snmp> |
| 18 |
<community alu:operation="replace"> |
| 19 |
<community-string>Sample Community</community-string> |
| 20 |
<access-permissions>r</access-permissions> |
| 21 |
<version>v2c</version> |
| 22 |
</community> |
| 23 |
</snmp> |
| 24 |
</security> |
| 25 |
</system> |
| 26 |
</configure> |
| 27 |
</config> |
| 28 |
""" |
| 29 |
|
| 30 |
|
| 31 |
def create_session(host, port, username, password): |
| 32 |
"""Creates and returns an ncclient manager session.""" |
| 33 |
return manager.connect( |
| 34 |
host=host, |
| 35 |
port=port, |
| 36 |
username=username, |
| 37 |
password=password, |
| 38 |
hostkey_verify=False, |
| 39 |
device_params={'name': 'sros'} |
| 40 |
) |
| 41 |
|
| 42 |
|
| 43 |
def edit_config(m, config_payload): |
| 44 |
"""Edits the configuration with the given payload.""" |
| 45 |
m.edit_config(target='candidate', config=config_payload) |
| 46 |
|
| 47 |
|
| 48 |
def commit_changes(m, comment=''): |
| 49 |
"""Commits changes with an optional comment.""" |
| 50 |
response = m.commit(comment=comment) |
| 51 |
logging.info(response) |
| 52 |
|
| 53 |
|
| 54 |
def main(): |
| 55 |
LOG_FORMAT = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s' |
| 56 |
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=LOG_FORMAT) |
| 57 |
|
| 58 |
try: |
| 59 |
with create_session(DEVICE_HOST, DEVICE_PORT, DEVICE_USER, DEVICE_PASS) as m: |
| 60 |
# Lock the configuration |
| 61 |
m.lock(target='candidate') |
| 62 |
|
| 63 |
# Edit the configuration |
| 64 |
edit_config(m, EDIT_CONFIG_PAYLOAD) |
| 65 |
|
| 66 |
# Commit the configuration |
| 67 |
commit_changes(m, comment='A sample commit comment goes here') |
| 68 |
|
| 69 |
# Unlock the configuration |
| 70 |
m.unlock(target='candidate') |
| 71 |
|
| 72 |
except Exception as e: |
| 73 |
logging.error(f"Encountered an error: {e}") |
| 74 |
|
| 75 |
|
| 76 |
if __name__ == '__main__': |
| 77 |
main() |