1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
11 from StringIO import StringIO
15 LOG = logging.getLogger(__name__)
18 def call(cmd, shell=False):
22 LOG.info(' '.join(cmd))
23 return subprocess.call(cmd, shell=shell)
26 def check_call(cmd, shell=False):
30 LOG.info(' '.join(cmd))
31 subprocess.check_call(cmd, shell=shell)
34 def check_output(cmd, shell=False):
38 LOG.info(' '.join(cmd))
39 return subprocess.check_output(cmd, shell=shell)
42 def check_and_kill(process):
43 cmd = "ps -ef | grep -v grep | awk '{print $8}' | grep -w %s | wc -l" % process
44 out = check_output(cmd, shell=True)
46 check_call(['killall', process])
49 def check_and_rmmod(mod):
50 cmd = "lsmod | awk '{print $1}' | grep -w %s | wc -l" % mod
51 out = check_output(cmd, shell=True)
53 check_call(['rmmod', mod])
57 mount_path_set = set()
58 out = check_output("cat /proc/mounts", shell=True)
64 mpath = line.split()[1]
65 mount_path_set.add(mpath)
66 if path in mount_path_set:
67 ret = call("umount %s" % path, shell=True)
72 class IPCommandHelper(object):
76 self.device_mac_map = {}
77 self.mac_device_map = {}
78 self.bdf_device_map = {}
79 self.device_bdf_map = {}
82 buf = check_output("ip link", shell=True)
83 macs = re.compile("[A-F0-9]{2}(?::[A-F0-9]{2}){5}", re.IGNORECASE | re.MULTILINE)
84 for mac in macs.findall(buf):
85 if mac.lower() in ('00:00:00:00:00:00', 'ff:ff:ff:ff:ff:ff'):
90 m = re.match(r'^\d+:(.*):.*', line)
91 if m and m.group(1).strip() != 'lo':
92 self.devices.append(m.group(1).strip())
93 for device, mac in zip(self.devices, self.macs):
94 self.device_mac_map[device] = mac
95 self.mac_device_map[mac] = device
96 for device in self.devices:
97 buf = check_output("ethtool -i %s" % device, shell=True)
98 bdfs = re.findall(r'^bus-info: \d{4}:(\d{2}:\d{2}\.\d*)$', buf, re.MULTILINE)
100 self.bdf_device_map[bdfs[0]] = device
101 self.device_bdf_map[device] = bdfs[0]
102 mac = self.device_mac_map[device]
103 self.mac_bdf_map[mac] = bdfs[0]
104 self.bdf_mac_map[bdfs[0]] = mac
107 if __name__ == '__main__':
108 ip_helper = IPCommandHelper()
109 print ip_helper.device_mac_map
110 print ip_helper.mac_device_map
111 print ip_helper.bdf_device_map
112 print ip_helper.device_bdf_map
113 print ip_helper.mac_bdf_map
114 print ip_helper.bdf_mac_map