Skip to content

Instantly share code, notes, and snippets.

@svinota
Created December 25, 2014 22:08
Show Gist options
  • Save svinota/2845813318d40ad2d8e6 to your computer and use it in GitHub Desktop.
Save svinota/2845813318d40ad2d8e6 to your computer and use it in GitHub Desktop.
def add_iface_to_netns(if_name, ns_name):
#
# init IPDB and netns
ipdb = IPDB()
netns = None
#
# try to perform the operation
try:
# NetNS() constructor also can raise exceptions,
# so put it under try/catch
#
netns = NetNS(ns_name)
#
# the code below can raise exceptions from IPDB
#
iface = ipdb.interfaces[if_name]
with iface as veth:
veth.net_ns_fd = netns.netns
except Exception as e:
print(e)
finally:
print("Release...")
#
# We should clean up ALL we spawned.
#
# The order doesn't matter, but matters did we close
# all IPDB and NetNS instances, or not:
#
ipdb.release()
#
# Close NetNS only if it was instantiated
#
if netns is not None:
netns.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment