赋值前引用的变量 'opts'

variable 'opts' referenced before assignment

下面的代码运行正常,除非我使用一个不受支持的选项提示 "UnboundLocalError: local variable 'opts' referenced before assignment" 错误。这是代码。代码运行良好并在使用 for o,a in opts

之前显示异常
import socket
import sys
import getopt
import threading
import subprocess

#define some global variables

listen              =False
command             =False
upload              =False
execute             =""
target              =""
upload_destination  =""
port                = 0

def usage():
    print("\nnetcat_replacement tool")
    print()
    print("Usage: netcat_replacement.py -t target_host -p port\n")
    print ("""-l --listen               - listen on [host]:[port] for
                            incoming connections""")
    print("""-e --execute=file_to_run  - execute the given file upon
                            receiving a connection""")
    print("""-c --command              - initialize a command shell""")
    print("""-u --upload=destination   - upon receiving connection upload a
                            file and write to [destination]""")
    print("\n\n")
    print("Examples: ")
    print("netcat_replacement.py -t 192.168.0.1 -p 5555 -l -c")
    print("netcat_replacement.py -t 192.168.0.1 -p 5555 -l -u=c:\target.exe")
    print('netcat_replacement.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd"')
    print("echo 'ABSDEFGHI' | ./netcat_replacement.py -t 192.168.0.1 -p 135")

def main():
    global listen
    global port
    global execute
    global command
    global upload_destination
    global target

    if not len(sys.argv[1:]):
        usage()

    #read the command line options
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu:",
        ["help","listen","execute", "target","port","command","upload"])
    except getopt.GetoptError as err:
        print(str(err).upper())
        usage()
    for o,a in opts:
        if o in ("-h", "--help"):
            usage()
        elif o in ("-l", "--listen"):
            listen=True
        elif o in ("-e", "--execute"):
            execute=a
        elif o in ("-c", "--commandshell"):
            command=True
        elif o in ("-u", "--upload"):
            upload_destination=a
        elif o in ("-t", "--target"):
            target=a
        elif o in ("-p", "--port"):
            port=int(a)
        else:
            assert False,"unhandled option"

main()

我做错了什么?

发生的事情是,您尝试在 try 块中定义 ops,但是发生异常并且您跳转到 except 块,因此它从未被定义.在此之后,您尝试在循环的后续行中访问它,但由于此时它未定义,您会得到 UnboundLocalError.

所以,你捕获了一个异常,通知用户发生了异常,然后实际上忘记了终止你的程序。

您想要做的是:

except getopt.GetoptError as err:
    print(str(err).upper())
    usage()

    return # <------ the return here

您将使用 return 跳出 main 而无需执行其后的任何代码,因为这正是您 不会 万一出现异常怎么办。