为什么我在检查界面时会收到语法错误?尝试用 Python/argparse 为 Linux 制作 MAC 转换器

Why am I getting a syntax error when I check my interface? Trying to make a MAC changer for Linux with Python/argparse

我正在制作一个 python 3.x 程序,该程序 运行 每隔几分钟就会在 Linux 中更改 MAC 的命令(如它的各种功能之一)。我仔细检查并安装了 ifconfig,所以这不是问题所在。这是让我悲伤的部分:

import sys
import subprocess
import argparse
import random
import time
import re

def macfunc():

    def get_args():
            #Get interface stuff
            prsr = argparse.ArgumentParser()
            prsr.add_argument("-i","--interface",dest="interface",help="Name of interface.")
            options = prsr.parse_args()
            if options.interface:
                return options.interface
            else:
                prsr.error("syntax error")
        def changer(interface, new_mac_address):
            #Does the terminal commands for changing the MAC
            subprocess.call(["sudo","ifconfig",interface,"down"])
            subprocess.call(["sudo","ifconfig",interface,"hw","ether",new_mac_address])
            subprocess.call(["sudo","ifconfig",interface,"up"])
        def get_random_mac():
            #Randomizes MAC
            charset="0123456789abcdef"
            random_mac="00"
            for i in range(5):
                random_mac += ":" + \
                              random.choice(charset) \
                              + random.choice(charset)
                return random_mac
        def get_original(interface):
            #Holds the current MAC for restoration purposes
            output=subprocess.check_output(["ifconfig",interface])
            return re.search("\w\w:\w\w:\w\w:\w\w:\w\w:\w\w",str(output)).group(0)
    
        #Now let's do the magic and change the mac every 2 minutes
        if __name__ == "__main__":
            print("Initializing MAC scrambler. Generating new MAC every 2 minutes.")
            sleeper=120
            interface=get_args()
            current_mac=get_original(interface)
            try:
                while True:
                    random_mac=get_random_mac()
                    change_mac(interface,random_mac)
                    new_mac_info=subprocess.check_output(["ifconfig",interface])
                    if random_mac in str(new_mac_info):
                        print("New MAC:",random_mac,end=" ")
                        sys.stdout.flush()
                        time.sleep(sleeper)
            except KeyboardInterrupt:
                change_mac(interface,current_mac)
                print("Original MAC restored. Terminating scrambling.")

macfunc()

每当我 运行 它时,我都会收到语法错误消息。我无法终生弄清楚我错过了什么。对我而言,这可能是非常愚蠢的事情。帮助将是粉碎的。

首先,你没有使用正确的缩进。与其在这种类型的简单程序中使用 argparse,我建议您使用自己的函数来执行此操作。而且,要获得当前 MAC 地址,您可以简单地 运行 此命令 cat /sys/class/net/{interface}/address 而不是使用 re.

import subprocess
import random
import time
import sys

def elementAfter(lst,element):  
    try:
        elementIndex = lst.index(element)

        elementAfter = lst[elementIndex + 1]
        return elementAfter
    except ValueError:
        return False

def change_mac(interface, new_mac_address):
    #Does the terminal commands for changing the MAC
    subprocess.call(["sudo","ifconfig",interface,"down"])
    subprocess.call(["sudo","ifconfig",interface,"hw","ether",new_mac_address])
    subprocess.call(["sudo","ifconfig",interface,"up"])

def get_random_mac():
    #Randomizes MAC
    charset="0123456789abcdef"
    random_mac="00"
    for i in range(5):
        random_mac += ":" + \
                      random.choice(charset) \
                      + random.choice(charset)
        return random_mac

def get_original(interface):
    #Holds the current MAC for restoration purposes
    currentMac = subprocess.run(f'cat /sys/class/net/{interface}/address', shell=True, capture_output=True)
    return currentMac.stdout.decode("utf-8").rstrip()

#Now let's do the magic and change the mac every 2 minutes
if __name__ == "__main__":
    print("Initializing MAC scrambler. Generating new MAC every 2 minutes.")
    sleeper=120
    interface=elementAfter(sys.argv,"-i") or elementAfter(sys.argv,"--interface")
    current_mac=get_original(interface)
    try:
        while True:
            random_mac=get_random_mac()
            change_mac(interface,random_mac)
            new_mac_info=subprocess.check_output(["ifconfig",interface])
            if random_mac in str(new_mac_info):
                print("New MAC:",random_mac,end=" ")
                sys.stdout.flush()
                time.sleep(sleeper)
    except KeyboardInterrupt:
        change_mac(interface,current_mac)
        print("Original MAC restored. Terminating scrambling.") 

我以不同的方式进行了处理,并取得了相同的预期结果!

import time
import subprocess
import random
import time
from getmac import get_mac_address as gma


#Look after the original MAC
original=(gma())
#Randomize a new address
charset="0123456789abcdef"
randommac="00"
for i in range(5):
    randommac += ":" +\
                    random.choice(charset)\
                    + random.choice(charset)
#do the terminal commands
def subproc():
    subprocess.call(["sudo","ifconfig","wlp3s0","down"])
    subprocess.call(["sudo","ifconfig","wlp3s0","hw","ether",randommac])
    subprocess.call(["sudo","ifconfig","wlp3s0","up"])
    
subproc()    
print("Your MAC has been cheesed. New MAC:" + randommac)
print("The new MAC will expire in 60 seconds and be reverted.")
print("KEEP THIS PROGRAM OPEN.")
time.sleep(60)
subprocess.call(["sudo","ifconfig","wlp3s0","down"])
subprocess.call(["sudo","ifconfig","wlp3s0","hw","ether",original])
subprocess.call(["sudo","ifconfig","wlp3s0","up"])
print("Old MAC restored:" + original)