用Python编写MAC地址修改程序

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()

posted @ 2022-03-28 17:29  Jason_huawen  阅读(998)  评论(0编辑  收藏  举报