arg未定义,argv列出一个。怎么了?

时间:2018-10-20 19:20:44

标签: python python-3.x

我是python和scapy的新手。我正在尝试制作DHCP饥饿脚本。只有我的论点行不通。我收到一个NameError:名称'arg'未定义错误。当我将arg更改为argv时,我只会得到一个列表。我在做什么错了?

#!/usr/bin/python3
from scapy.all import *
import sys
import time
import getopt


def main(argv):
    conf.checkIPaddr = False   
    brmac = 'ff:ff:ff:ff:ff:ff'
    network = ""
    serverid = ""
    begin = 1
    end = 1

    try:
       opts, args = getopt.getopt(argv,"hnsb:e:")
    except getopt.GetoptError:
       print("dhcp.py -n 192.168.1. -s 192.168.1.1 -b 20 -e 250")
        sys.exit(2)
    for opt, args in opts:
        if opt == "-h":
            print("dhcp.py -n 192.168.1. -s 192.168.1.1 -b 20 -e 250")
            sys.exit()
        elif opt in ("-n"):
            network = arg
        elif opt in("-s"):
            serverid = arg 
        elif opt in ("-b"):
            begin = arg
        elif opt in("e"):  
            end = arg
    for ip in range(int(begin), int(end)):
        adr = RandMAC()
        sendp(Ether(src=adr, dst=brmac)/IP(src='0.0.0.0', dst='255.255.255.255')/UDP(sport=68, dport=67)/BOOTP(chaddr=adr)/DHCP(options=[('message-type', 'request'),("server_id",str(serverid)), ("requested_addr",str(network) + str(ip)), 'end']))
        print("requesting ip " + str(network) + str(ip))
        time.sleep(2)



if __name__ == "__main__":
   main(sys.argv[1:])

1 个答案:

答案 0 :(得分:1)

您正在使用for opt, args in opts:作为for循环,但是在该for循环中,您尝试将args称为arg,而这并不存在。

可以解决您的错误的解决方案:

  • 将for循环内的arg更改为args,以使其与for循环中的变量匹配
  • 将变量名args更改为arg,使其与您代码中的变量匹配