【问题标题】:variable 'opts' referenced before assignment赋值前引用的变量“opts”
【发布时间】:2017-07-13 22:55:28
【问题描述】:

下面的代码运行良好,除非我使用不支持的选项提示 “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

标签: python getopts


【解决方案1】:

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

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

你想做的事情是这样的:

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

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

您将使用 return 突破 main 而不执行它后面的任何代码,因为这正是您在发生异常时所做的事情。 p>

【讨论】:

  • 感谢您的反馈。这就是问题所在。一旦我添加了返回线,问题就解决了。感谢您的帮助
  • @IpSp00f3r 很高兴为您提供帮助!
猜你喜欢
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
  • 2011-11-06
  • 2018-01-12
  • 2021-07-23
  • 1970-01-01
相关资源
最近更新 更多