利用Subprocess以及re正则表达式模块实现MAC地址修改工具
本代码的作用是修改Linux操作系统的MAC地址,主要由以下部分组成:
1. 需要首先对用户输入的参数进行合法性判断,比如输入的接口在本机是否存在,以及输入的MAC地址是否为合法的MAC地址
2. 利用re模块提取MAC地址
3. 利用subprocess的run方法执行修改MAC地址的命令,可以传递列表作为参数,以列表形式作为参数更加安全,不会被恶意注入其他的命令。
4. 验证是否修改成功,通过判断修改前后的MAC地址是否相等即可。
1 import subprocess 2 import re 3 import optparse 4 import sys 5 6 class MACChanger: 7 def __init__(self) -> None: 8 self.interface, self.new_mac_address = self.get_params() 9 10 def get_params(self): 11 parser = optparse.OptionParser('Usage: < Program > -i interface -m new mac address') 12 parser.add_option('-i', '--interface', dest='interface', type='string', help='Specify interface to change MAC address') 13 parser.add_option('-m', '--newmac', dest='newmac', type='string', help='Specify new mac address to change') 14 options, args = parser.parse_args() 15 if options.interface is None or options.newmac is None: 16 print(parser.usage) 17 sys.exit(0) 18 19 if self.check_interface(options.interface) and self.check_mac_valid(options.newmac): 20 21 return options.interface, options.newmac 22 23 def check_interface(self, interface): 24 try: 25 res = subprocess.check_output('ifconfig ' + interface, shell=True, stderr=subprocess.STDOUT) 26 return True 27 except: 28 print('[-] The interface does not exist') 29 sys.exit(0) 30 31 def check_mac_valid(self, mac_address): 32 pattern = r'\w\w:\w\w:\w\w:\w\w:\w\w:\w\w' 33 res = re.match(pattern, mac_address) 34 if res: 35 return True 36 else: 37 return False 38 39 def get_current_mac(self): 40 try: 41 command = "ifconfig %s" % self.interface 42 result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT).decode('utf-8') 43 pattern = r'\w\w:\w\w:\w\w:\w\w:\w\w:\w\w' 44 mac_address = re.search(pattern, result).group(0) 45 46 return mac_address 47 48 except Exception as e: 49 print(e) 50 sys.exit(0) 51 52 def change_mac(self): 53 try: 54 subprocess.run(['ifconfig', self.interface, 'down']) 55 subprocess.run(['ifconfig', self.interface, 'hw', 'ether', self.new_mac_address]) 56 subprocess.run(['ifconfig', self.interface, 'up']) 57 58 except Exception as e: 59 print(e) 60 sys.exit(0) 61 62 def run(self): 63 print("Current MAC address: %s" % self.get_current_mac()) 64 self.change_mac() 65 if self.new_mac_address == self.get_current_mac(): 66 print("[-] Successfully changed MAC address") 67 else: 68 print('[-] Failed to change MAC') 69 70 71 if __name__ == '__main__': 72 macchanger = MACChanger() 73 macchanger.run()
STRIVE FOR PROGRESS,NOT FOR PERFECTION