在赋值之前引用的变量'opts'

时间:2017-07-13 22:55:29

标签: python getopts

下面的代码运行正常,除非我使用了一个不受支持的选项,该选项会在分配“错误之前提示”UnboundLocalError:局部变量'opts'。这是代码。代码工作正常并在使用o之前显示异常,a在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()

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您会尝试在ops块中定义try,但会发生异常并跳转到except块,因此无法定义。在此之后,您尝试在循环中的后续行中访问它,但由于此时未定义,因此您将获得UnboundLocalError

因此,您捕获异常,通知用户发生异常,然后实际忘记终止您的程序。

你想要做的是:

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

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

您将使用返回来突破main而不执行其后的任何代码,因为这正是您在发生异常时的内容。