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
interface
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_interface
instead of
interface
.
To convert the interface, the Python code in this excerpt does the following:
Defines a JSON object that specifies attributes and values associated with layer 2 interface.
l2interface_data = {"routing": False, "vrf": None}
Uses a PUT request to replace the existing layer 3 interface. The layer 2 interface attributes are specified in the JSON object. Because the other writable attributes are not specified, those other interface 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/v10.04/".format(ip_address)
# the target interface
interface = "1/1/1"
# escape slash character for uri
converted_interface = interface.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 interface in JSON format
l2interface_data = {"routing": False, "vrf": None}
# PUT call to move the target interface from L3 to L2
uri = base_url + "system/interfaces/{}".format(converted_port)
s.put(uri, json=l2interface_data, verify=False)
finally:
# logout
s.post(base_url + "logout", verify=False)
if __name__ == "__main__":
main()