예제 #1
0
def main():
    parser = Parser(__file__)
    args = parser.parse_args()

    session = NetconfSSHSession(args.host, args.port, args.user, args.password)

    es_nsmap = {'yp': 'urn:ietf:params:xml:ns:yang:ietf-yang-push'}
    root = lxml.etree.Element(
        'establish-subscription',
        nsmap=es_nsmap,
        attrib={
            'xmlns':
            'urn:ietf:params:xml:ns:yang:ietf-subscribed-notifications'
        })

    datastore = util.leaf_elm('yp:datastore', 'ds:operational')
    root.append(datastore)

    datastore_xpath_filter = util.leaf_elm('yp:datastore-xpath-filter',
                                           args.xpath)

    root.append(datastore_xpath_filter)

    periodic = util.subelm(root, 'yp:periodic')
    period = util.leaf_elm("yp:period", args.period)
    periodic.append(period)

    res = session.send_rpc(root)

    while True:
        tree, notif, msg = session.get_notification()
        print(etree.tounicode(notif, pretty_print=True), end="\n\n")
예제 #2
0
 def receive_notifications(self, session: NetconfSSHSession, subscription_id: int):
     while True:
         try:
             notif = session.get_notification(subscription_id)
             for handler in self.handlers:
                 handler(notif, subscription_id, "/")
         except:
             traceback.print_exc()
             break
예제 #3
0
    def open_session(self, params):
        next_session_id = max(self.session_sockets.keys()) + 1 if self.session_sockets else 1

        res = {"status": None}
        try:
            sess = NetconfSSHSession(params['host'], params['port'], params['username'], params['password'])
            self.session_sockets[next_session_id] = sess
            self.sessions[next_session_id] = {
                "session_id" : next_session_id,
                "host": params['host'],
                "port": params['port'],
                "subscriptions": []
            }

            res["status"] = "ok"
            res["session_id"] = next_session_id
        except Exception as e:
            res["status"] = "error"
            res["msg"] = str(e)
        return res
예제 #4
0
from netconf.client import NetconfSSHSession
from lxml import etree

session = NetconfSSHSession("localhost", "8300", "admin", "admin")
config = session.get()

# TODO: Catch the RPCerror exception.
print(type(config))
print(etree.tostring(config, pretty_print=True))
session.close()
예제 #5
0
    :type session: NetconfSSHSession
    :param filename: configuration file
    :type filename: str
    :return: configuration datastore
    :rtype:
    """
    print("---DELETE---")
    xml = etree.parse(folder + filename)
    config = session.edit_config(method='delete',
                                 newconf=etree.tostring(xml).decode("utf-8"))
    return etree.tostring(config).decode("utf-8")


if __name__ == '__main__':
    # connection to NETCONF servers
    session_1 = NetconfSSHSession(host_1, port, username, password)
    session_2 = NetconfSSHSession(host_2, port, username, password)

    # create operations
    print(create_config(session_1, create_1))
    time.sleep(ts)
    print(create_config(session_2, create_1))
    time.sleep(td)

    # get operations
    print(get_config(session_1))
    time.sleep(ts)
    print(get_config(session_2))
    time.sleep(td)

    # merge oeprations
예제 #6
0
boot_img.append(util.leaf_elm("os-version", "16.8"))
boot_img.append(util.leaf_elm("download-uri", "tftp://10.0.0.1/files"))
img_verification = util.subelm(boot_img, "image-verification")
img_verification.append(util.leaf_elm("hash-algorithm", "md5"))
img_verification.append(util.leaf_elm("hash-value", "12345678"))

onboard.append(util.leaf_elm("configuration-handling", "append"))
onboard.append(util.leaf_elm("pre-configuration-script", "pre.py"))
onboard.append(util.leaf_elm("configuration", "tbd"))
onboard.append(util.leaf_elm("post-configuration-script", "post.py"))

#print (type(data))
print(etree.tounicode(data, pretty_print=True))
exit()

session = NetconfSSHSession("172.17.0.2", "8300", "admin", "admin", debug=True)
#reply = session.get_config()
#root, reply, replystring = session.send_rpc("<my-cool-rpc/>")

#root, reply, replystring = session.send_rpc("<bootstrap/>")
root, reply, replystring = session.send_rpc(data)

session.close()

reply_list = list(reply)
for e in reply_list:
    print(e.tag, e.attrib, e.text)
print("\n")
dataElem = reply_list[0]

dataElem = reply.find("nc:data", namespaces=NSMAP)
예제 #7
0
# Utility to close Netconf sessions
def close_netconf_session(session):
    # Let's take the reference of the transport
    transport = session.pkt_stream.stream
    # Let's close the Netconf session
    session.close()
    # This is a workaround for RST_ACK
    time.sleep(0.05)
    # Close the transport
    transport.close()
    # Flush the cache
    transport.cache.flush()


# Let's create a NetConf session
session = NetconfSSHSession("127.0.0.1", 830, "srv6", "srv6")

# From the hello, we got the capabilities
for capability in session.capabilities:
    print capability

config = """
<edit-config>
<target>
  <running/>
</target>
<default-operation>none</default-operation>
<test-option>test-then-set</test-option>
<error-option>rollback-on-error</error-option>
<config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
  <srv6-explicit-path operation="create" xmlns="urn:ietf:params:xml:ns:yang:srv6-explicit-path">
예제 #8
0
def main(args):

    if not args:
        return
    #print(type(args))
    #return

    #TODO: check if args is a valid IP

    nsmap_add("sys", "urn:ietf:params:xml:ns:yang:ietf-system")
    MODEL_NS = "urn:my-urn:my-model"
    nsmap_add('pfx', MODEL_NS)

    keyFileToSend = "python/cwCA/intermediate/certs/www.ap.controlware.com.cert.pem"
    privateKeyFile = "/usr/src/app/python/vendorCA/intermediate/private/www.ownership.vendor1.com.key.pem"

    fileString = getCertStringfromFile(keyFileToSend)

    sign = signString(privateKeyFile, b"password", fileString.encode('ascii'),
                      "sha256")

    #Encode signature so it can be send as a string
    sign_base64 = base64.b64encode(sign)
    utf8Signature = sign_base64.decode('utf-8')
    ownershipRPC = util.elm("ownership")
    cert = OpenSSL.crypto.load_certificate(
        OpenSSL.crypto.FILETYPE_PEM,
        getCertStringfromFile(
            '/usr/src/app/python/vendorCA/intermediate/certs/www.ownership.vendor1.com.cert.pem'
        ))
    #if verifyString(cert, sign, fileString.encode('ascii'),"sha256"):
    if verifyString(
            '/usr/src/app/python/vendorCA/intermediate/certs/www.ownership.vendor1.com.cert.pem',
            sign, fileString.encode('ascii'), "sha256"):
        ownerCertificate = util.subelm(ownershipRPC, "ownerCertificate")
        ownerCertificate.append(util.leaf_elm("certificate", fileString))
        #ownerCertificate.append(util.leaf_elm("certificateSignature", sign_base64))
        ownerCertificate.append(
            util.leaf_elm("certificateSignature", utf8Signature))

    bootstrapRPC = util.elm("bootstrap")
    bootInfo = util.subelm(bootstrapRPC, "bootInfo")

    #bootInfo_base64 = base64.b64encode(asnString)
    bytebootstrapArtifact = buildbootstrapArtifact()
    bootInfo_base64 = base64.b64encode(bytebootstrapArtifact)
    utf8BootInfo = bootInfo_base64.decode('utf-8')

    privateKeyFile = "/usr/src/app/python/cwCA/intermediate/private/www.ap.controlware.com.key.pem"
    sign = signString(privateKeyFile, b"password",
                      utf8BootInfo.encode('ascii'), "sha256")
    sign_base64 = base64.b64encode(sign)
    utf8Signature = sign_base64.decode('utf-8')

    bootInfo.append(util.leaf_elm("bootInfoASN", utf8BootInfo))

    if verifyString(
            '/usr/src/app/python/cwCA/intermediate/certs/www.ap.controlware.com.cert.pem',
            sign, utf8BootInfo.encode('ascii'), "sha256"):
        bootInfo.append(util.leaf_elm("bootInfoSignature", utf8Signature))

    #TODO: not hardcode
    session = NetconfSSHSession(args, "8300", "admin", "admin", debug=True)
    root, reply, replystring = session.send_rpc(ownershipRPC)
    root, reply, replystring = session.send_rpc(bootstrapRPC)
    session.close()

    dataElem = reply.find("nc:data", namespaces=NSMAP)
    x = dataElem.find("nc:result", namespaces=NSMAP)
    if x is not None:
        print(x.text)
    else:
        print("not found")
예제 #9
0
from lxml import etree
from netconf.client import NetconfSSHSession

__author__ = "Ricard Vilalta <*****@*****.**>"
__copyright__ = "Copyright 2018, CTTC"

# connexion parameters
host = 'localhost'
port = 2022
username = "******"
password = "******"

# connexion to servers
session = NetconfSSHSession(host, port, username, password)

# servers capabilities
c = session.capabilities
print(c)

# get config
print("---GET CONFIG---")
config = session.get_config()
xmlstr = etree.tostring(config, encoding='utf8', xml_declaration=True)
print(xmlstr)

# edit config
new_config = '''
<config>
    <topology xmlns="urn:topology">
        <node operation="merge"> <!-- modify with delete -->
            <node-id>10.1.7.64</node-id>
예제 #10
0
from lxml import etree
from netconf.client import NetconfSSHSession

__author__ = "Laura Rodriguez Navas <*****@*****.**>"
__copyright__ = "Copyright 2018, CTTC"

# connexion parameters
host = '10.1.7.64'
port = 830
username = "******"
password = "******"

# connexion to servers
session = NetconfSSHSession(host, port, username, password)

# servers capabilities
c = session.capabilities
print(c)

# get config
print("---GET CONFIG---")
config = session.get_config()
xmlstr = etree.tostring(config, encoding='utf8', xml_declaration=True)
print(xmlstr)

# edit config
print("---EDIT CONFIG---")
xml = etree.parse('new_config.xml')  # new configuration
config = session.edit_config(method='none', newconf=etree.tostring(xml))
xmlstr = etree.tostring(config, encoding='utf8', xml_declaration=True)
print(xmlstr)
예제 #11
0
def add(communicationType):
    if communicationType == "non persistent sequential":
        for i in range(1, _NumberOfRuleToBeEnforced + 1):
            config = """
      <edit-config>
      <target>
        <running/>
      </target>
      <default-operation>none</default-operation>
      <test-option>test-then-set</test-option>
      <error-option>rollback-on-error</error-option>
      <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
        <srv6-explicit-path operation="create" xmlns="urn:ietf:params:xml:ns:yang:srv6-explicit-path">
            <path>
                <destination>%s</destination>
                <sr-path>
                    <srv6-segment>%s</srv6-segment>
                </sr-path>
                <encapmode>inline</encapmode>
                <device>%s</device>
            </path>
          </srv6-explicit-path>
      </config>
      </edit-config>
      """ % (_Prefix + str(i) + '/128', _Segments, _Device)

            session = NetconfSSHSession(_ServerIP, _Port, _Username, _Password)
            session.send_rpc(config)
            close_netconf_session(session)

    elif communicationType == "non persistent bulk":
        config = """
      <edit-config>
      <target>
        <running/>
      </target>
      <default-operation>none</default-operation>
      <test-option>test-then-set</test-option>
      <error-option>rollback-on-error</error-option>
      <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
        <srv6-explicit-path operation="create" xmlns="urn:ietf:params:xml:ns:yang:srv6-explicit-path">
            <path>
                <destination>%s</destination>
                <sr-path>
                    <srv6-segment>%s</srv6-segment>
                </sr-path>
                <encapmode>inline</encapmode>
                <device>%s</device>
            </path>
      """ % (_Prefix + str(1) + '/128', _Segments, _Device)
        for i in range(2, _NumberOfRuleToBeEnforced + 1):
            config += """
        <path>
            <destination>%s</destination>
            <sr-path>
                <srv6-segment>%s</srv6-segment>
            </sr-path>
            <encapmode>inline</encapmode>
            <device>%s</device>
        </path>
      """ % (_Prefix + str(i) + '/128', _Segments, _Device)
        config += """
        </srv6-explicit-path>
    </config>
    </edit-config>
    """
        session = NetconfSSHSession(_ServerIP, _Port, _Username, _Password)
        session.send_rpc(config)
        close_netconf_session(session)

    elif communicationType == "persistent Conncection":
        session = NetconfSSHSession(_ServerIP, _Port, _Username, _Password)
        for i in range(1, _NumberOfRuleToBeEnforced + 1):
            config = """
      <edit-config>
      <target>
        <running/>
      </target>
      <default-operation>none</default-operation>
      <test-option>test-then-set</test-option>
      <error-option>rollback-on-error</error-option>
      <config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
        <srv6-explicit-path operation="create" xmlns="urn:ietf:params:xml:ns:yang:srv6-explicit-path">
            <path>
                <destination>%s</destination>
                <sr-path>
                    <srv6-segment>%s</srv6-segment>
                </sr-path>
                <encapmode>inline</encapmode>
                <device>%s</device>
            </path>
          </srv6-explicit-path>
      </config>
      </edit-config>
      """ % (_Prefix + str(i) + '/128', _Segments, _Device)

            session.send_rpc(config)
        close_netconf_session(session)
예제 #12
0
from netconf.client import NetconfSSHSession
import xmltodict
from xmljson import badgerfish as bf
from lxml import etree
with open('tests/testdata2.xml', 'r') as file:
    data = file.read().replace('\n', '')

etreeX = etree.parse('tests/testdata2.xml')

#print(type(etreeX[0]))
newconf = etreeX.getroot()
print(etree.tostring(newconf, pretty_print=True))

session = NetconfSSHSession("localhost", "8300", "admin", "admin")
edit_config_response = session.edit_config(newconf=data)

print(etree.tostring(edit_config_response, pretty_print=True))
session.close()
from netconf.client import NetconfSSHSession

from lxml import etree

session = NetconfSSHSession("localhost", "8300", "admin", "admin")
config = session.get_config(select='<components xmlns="http://openconfig.net/yang/platform"><component><name>shelf-sh41</name><config/></component></components>')

#dom = xml.dom.minidom.parseString(config)

#print(dom.toprettyxml())

print(etree.tostring(config, pretty_print=True))
session.close()
예제 #14
0
from netconf.client import NetconfSSHSession

host = '192.168.5.41'
port = 8300
username = '******'
password = '******'

try:
	session = NetconfSSHSession(host, port, username, password)
	#config = session.get_config()
	config = session.edit_config('adf')
	print(config)
except Exception as e:        
	print(e)

예제 #15
0
username = "******"
password = "******"


def addConnection(connectionid, port_in_id, port_out_out, transceiverid):
    print("CREATE CONNECTION " + connectionid)
    node_con = node_connectivity()
    node_con.connection.add(connectionid)
    node_con.connection[connectionid].port_in_id = port_in_id
    node_con.connection[connectionid].port_out_out = port_out_out
    node_con.connection[connectionid].transceiver = transceiverid
    return node_con


if __name__ == '__main__':
    session = NetconfSSHSession(host, port, username, password)
    c = addConnection("5001", "65792", "65536", "1")
    c2 = addConnection("5002", "65536", "65792", "1")
    c3 = addConnection("5003", "65536", "65792", "1")
    c4 = addConnection("5004", "65536", "65792", "1")

    opC = 'create'
    opD = 'delete'
    print("--EDIT CONFIG 1--")
    config = session.edit_config(method=opC,
                                 newconf=pybindIETFXMLEncoder.serialise(c))
    xmlstr = etree.tostring(config, encoding='utf8', xml_declaration=True)
    print(xmlstr)

    print("--EDIT CONFIG 2--")
    config = session.edit_config(method=opC,