Example: Changing an interface from layer 3 to layer 2

The following example is an excerpt of Python code that changes an existing interface from a layer 3 interface to a layer 2 interface.

The port variable was defined using the standard port notation, which uses slashes. However, in REST URIs, the slash must be replaced by its percent-encoded equivalent, %2F. Therefore the variable used to represent the port in this code is convert_port instead of port.

To convert the interface, the Python code in this excerpt does the following:

  1. Defines a JSON object that specifies attributes and values associated with layer 2 ports.

    l2port_data = {"routing": False, "vrf": None}
  2. Uses a PUT request to replace the existing layer 3 port. The layer 2 port attributes are specified in the JSON object. Because the other mutable port attributes are not specified, those other port attributes are either removed (if there are no default values) or are set to their default values.

The code also handles logging into the switch, handling the session cookie, disabling switch certificate verification for every request (using the verify=False parameter), and logging out of the switch. The code in this excerpt uses the requests library.

#!/usr/bin/python
import requests
import urllib3

def main():
    # ip address of the switch
    ip_address = "192.168.2.101"

    # switch credentials
    credentials = {"username": "admin", "password": "admin"}

    # base url
    base_url = "https://{0}/rest/v1/".format(ip_address)

    # the target port
    port = "1/1/1"

    # escape slash character for uri
    converted_port = port.replace("/", "%2F")

    # requests session so cookie is persisted between calls
    s = requests.Session()

    try:
        # login
        s.post(base_url + "login", params=credentials, verify=False)

        # layer 2 data for the target port in JSON format
        l2port_data = {"routing": False, "vrf": None}

        # PUT call to move the target port from L3 to L2
        uri = base_url + "system/ports/{}".format(converted_port)
        s.put(uri, json=l2port_data, verify=False)

    finally:

        # logout
        s.post(base_url + "logout", verify=False)


if __name__ == "__main__":
    main()