7 from StringIO import StringIO
11 LOG = logging.getLogger(__name__)
14 def call(cmd, shell=False):
18 LOG.info(' '.join(cmd))
19 return subprocess.call(cmd, shell=shell)
22 def check_call(cmd, shell=False):
26 LOG.info(' '.join(cmd))
27 subprocess.check_call(cmd, shell=shell)
30 def check_output(cmd, shell=False):
34 LOG.info(' '.join(cmd))
35 return subprocess.check_output(cmd, shell=shell)
38 def check_and_kill(process):
39 cmd = "ps -ef | grep -v grep | awk '{print $8}' | grep -w %s | wc -l" % process
40 out = check_output(cmd, shell=True)
42 check_call(['killall', process])
45 def check_and_rmmod(mod):
46 cmd = "lsmod | awk '{print $1}' | grep -w %s | wc -l" % mod
47 out = check_output(cmd, shell=True)
49 check_call(['rmmod', mod])
53 mount_path_set = set()
54 out = check_output("cat /proc/mounts", shell=True)
60 mpath = line.split()[1]
61 mount_path_set.add(mpath)
62 if path in mount_path_set:
63 ret = call("umount %s" % path, shell=True)
68 class IPCommandHelper(object):
72 self.device_mac_map = {}
73 self.mac_device_map = {}
74 self.bdf_device_map = {}
75 self.device_bdf_map = {}
78 buf = check_output("ip link", shell=True)
79 macs = re.compile("[A-F0-9]{2}(?::[A-F0-9]{2}){5}", re.IGNORECASE | re.MULTILINE)
80 for mac in macs.findall(buf):
81 if mac.lower() in ('00:00:00:00:00:00', 'ff:ff:ff:ff:ff:ff'):
86 m = re.match(r'^\d+:(.*):.*', line)
87 if m and m.group(1).strip() != 'lo':
88 self.devices.append(m.group(1).strip())
89 for device, mac in zip(self.devices, self.macs):
90 self.device_mac_map[device] = mac
91 self.mac_device_map[mac] = device
92 for device in self.devices:
93 buf = check_output("ethtool -i %s" % device, shell=True)
94 bdfs = re.findall(r'^bus-info: \d{4}:(\d{2}:\d{2}\.\d*)$', buf, re.MULTILINE)
96 self.bdf_device_map[bdfs[0]] = device
97 self.device_bdf_map[device] = bdfs[0]
98 mac = self.device_mac_map[device]
99 self.mac_bdf_map[mac] = bdfs[0]
100 self.bdf_mac_map[bdfs[0]] = mac
103 if __name__ == '__main__':
104 ip_helper = IPCommandHelper()
105 print ip_helper.device_mac_map
106 print ip_helper.mac_device_map
107 print ip_helper.bdf_device_map
108 print ip_helper.device_bdf_map
109 print ip_helper.mac_bdf_map
110 print ip_helper.bdf_mac_map