1. 程式人生 > 其它 >以Python面向物件思想編寫的MAC地址修改程式

以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的地址
        """
        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()