2017-07-13 30 views
1

下面的代碼運行正常,除非我使用不支持的選項,該選項會提示「在分配」錯誤之前引用「UnboundLocalError:本地變量」opts「。這是代碼。代碼工作正常,並顯示使用前的例外o,選擇在賦值之前引用的變量'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() 

我做錯了什麼?

+0

請顯示完整的堆棧跟蹤並在出現錯誤時標記該行。 –

+0

並有你的答案。它進入了異常,因此從未定義過try塊中的'ops'。 –

回答

0

會發生什麼情況是,您嘗試在try塊中定義ops,但會發生異常並跳轉到except塊,因此它不會被定義。在此之後,您嘗試在循環中的後續行中訪問它,但由於此處未定義,因此您將獲得UnboundLocalError

因此,您捕獲一個異常,通知用戶發生異常,然後實際上忘記終止您的程序。

你想要做的是沿着線的東西:

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

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

您將使用回打出來的main不執行任何代碼的下面,因爲那正是你不要什麼在發生例外。

+0

感謝您的反饋。這是問題。一旦我添加了返回線,問題就解決了。感謝您的幫助 – IpSp00f3r

+0

@ IpSp00f3r很高興爲您提供幫助! –

相關問題