1# SPDX-License-Identifier: GPL-2.0 2 3from .utils import ip 4import random 5import string 6 7 8class NetNS: 9 def __init__(self, name=None): 10 if name: 11 self.name = name 12 else: 13 self.name = ''.join(random.choice(string.ascii_lowercase) for _ in range(8)) 14 ip('netns add ' + self.name) 15 16 def __del__(self): 17 if self.name: 18 ip('netns del ' + self.name) 19 self.name = None 20 21 def __enter__(self): 22 return self 23 24 def __exit__(self, ex_type, ex_value, ex_tb): 25 self.__del__() 26 27 def __str__(self): 28 return self.name 29 30 def __repr__(self): 31 return f"NetNS({self.name})" 32