import subprocess #利用內置subprocess模塊執行Linux命令以修改MAC地址
import sys
import optparse #處理輸入參數
class MacChanger:
"""
Args:
interface: 要准備修改MAC地址的接口名稱
"""
def __init__(self, interface):
self.interface = interface
def get_mac_address(self):
"""
通過管道不同的命令獲得接口的mac的地址 或者可以用正則表達式提取出MAC地址
"""
res = subprocess.check_output("ifconfig %s| grep ether | awk -F ' ' '{print $2}'"%self.interface, shell=True, stderr=subprocess.STDOUT).decode('utf-8')
return res
def change_mac_address(self, new_mac_address):
subprocess.run(['ifconfig', self.interface, 'down'])
subprocess.run(['ifconfig', self.interface, 'hw', 'ether', new_mac_address])
subprocess.run(['ifconfig', self.interface, 'up'])
def run(self):
if sys.platform == 'linux': #該程序所用到的命令僅適用於linux,所以在執行修改MAC地址之前,首先判斷一下OS的類型
current_mac_addres = self.get_mac_address() #獲得現有的MAC地址
print("Current MAC Address Is: %s" % current_mac_addres)
new_mac_address = input("Enter MAC Address To Change: ")
self.change_mac_address(new_mac_address) #調用修改地址的方法
updated_mac_address = self.get_mac_address()
if updated_mac_address != current_mac_addres:
print("Succeed to change the MAC")
else:
print("Failed to change MAC address!")
else:
print("The program does not support the os!")
print("Exit the program!")
sys.exit()
if __name__ == "__main__":
banner = """
****************************
MAC Changer By Jason
****************************
"""
print(banner)
parser = optparse.OptionParser(usage="<prog -i interface>")
parser.add_option('-i','--interface',dest='interface', type='string', help='Specity Interface to Change MAC address')
options, args = parser.parse_args()
if not options.interface:
print("Please input interface as argument!")
print("Exit the program")
sys.exit()
interface = options.interface
mac_changer = MacChanger(interface)
mac_changer.run()