2017-07-13 17 views
1

"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() 

私は間違っていますか?ある何が起こる

+0

完全なスタックトレースを表示して、エラーが発生したときにウィークポイントに行をマークしてください。 –

+0

あなたの答えがあります。例外に入ったので、tryブロックにある 'ops'は決して定義されませんでした。 –

答えて

0

は、あなたがtryブロックにopsを定義しようとしますが、例外が発生すると、あなたはexceptブロックにジャンプし、それは今までに定義されていません。その後、ループの後続の行でその行にアクセスしようとしますが、その時点では未定義であるため、UnboundLocalErrorを取得します。

したがって、例外を検出し、例外が発生したことをユーザーに通知し、実際にプログラムを終了するのを忘れてしまいます。あなたがしたいと思い何

はの線に沿って何かである:

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

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

それはまさにあなたですので、あなたは、それ以下のコードのいずれかを実行せずにmainから抜け出すためにリターンを使用しますdo not例外が発生した場合。

+0

ご意見ありがとうございます。これが問題でした。リターンラインを追加すると、問題は解決されました。あなたの助けを歓迎します – IpSp00f3r

+0

@ IpSp00f3r喜んで助けてください! –

関連する問題