Creating a socket in a Python script defaults to the management interface. You can change the VR when the socket is create by using the following example:
import IN from socket import * udp_sock = socket(AF_INET, SOCK_DGRAM) udp_sock.setsockopt(SOL_SOCKET,IN.SO_BINDTODEVICE,"vrf_258") . . . # your program here . . . udp_sock.close()
Note
Do not use os.system('echo 2 > /proc/self/ns_id‘) to do this because os.system() spawns a subprocess. The subprocess will switch to vr-default, and then exit. The calling process will still be using the same VR as before.Using VRF_258 maps the socket to VR-Default.
In cases where the socket needs to be mapped to a user VR, include the followiung API in the script to get the VR name in kernel.
import exsh def vrfNameFromvrName(vrName): lst = exsh.clicmd("debug cli show namespace vrId | begin namespaceEntry", True) lines = lst.split('\n') # ignore first two lines lines.pop(0) lines.pop(0) vrfName = None for line in lines: if line == "": break name, id, peer = line.split() if name == vrName: vrfName = "vrf_" + str(256 + (int(id))) break return vrfName