Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 与子进程一起运行的python2.7 netcat程序_Python 2.7_Sockets_Subprocess - Fatal编程技术网

Python 2.7 与子进程一起运行的python2.7 netcat程序

Python 2.7 与子进程一起运行的python2.7 netcat程序,python-2.7,sockets,subprocess,Python 2.7,Sockets,Subprocess,我试图制作一个脚本来模仿netcat,它运行起来有点像,但我没有得到我想要的结果,当我尝试调试它时,我设法做了一点,但经过几天的搜索、尝试和错误之后,我对如何修复这个问题不知所措。这是我的全部代码: import sys import socket import getopt import threading import subprocess import os # define the global variables listen = False command = False

我试图制作一个脚本来模仿netcat,它运行起来有点像,但我没有得到我想要的结果,当我尝试调试它时,我设法做了一点,但经过几天的搜索、尝试和错误之后,我对如何修复这个问题不知所措。这是我的全部代码:

    import sys
import socket
import getopt
import threading
import subprocess
import os

# define the global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0


def usage():
    print "BHP Net Tool"
    print "Usage: netcat2.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 receiving connection upload a 
file and wrtie to [destination]"
    print "Examples: "
    print "netcat2.py -t 192.168.0.1 -p 5555 -l -c"
    print "netcat2.py -t 192.168.0.1 -p 5555 -l -u=C:\\target.exe"
    print "netcat2.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
    print "echo 'ABCDEFGHI' | ./netcat2.py -t 192.168.0.1 -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()

    # read the commandline option
    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"

    # are we going to listen or just send data from stdin?
    if not listen and len(target) and port > 0:
        # read in the line from the commandline
        # this will block, so send CTRL-D if not sending input
        # to stdin
        line = sys.stdin.readline()
        print (line)

        # send data off
        client_sender(line)

    # we are going to listen and potentially
    # upload things, execute commands, and drop a shell back
    # depending on our command line options above
    if listen:
        server_loop()


 def client_sender(line):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # connect to our target host
        client.connect((target, port))

        if len(line):
            client.send(line)
        while True:

            # now wait for data back
            recv_len = 1
            response = ""

            while recv_len:

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

                if recv_len < 4096:
                    break

            print "response"

            # wait for more input
            line = raw_input("")
            line += "\n"

            # send it off
            client.sendline()

    except:
        print "[*] Exception! Exiting."
        # tear down the connection
        client.close()


def server_loop():
    global target

    # if no target is defined, we listen on all interfaces
    if not len(target):
        target = "0.0.0.0"

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

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

        # spin off a thread to handle out new client
        client_thread = threading.Thread(target=client_handler, args=
 (client_socket,))
        client_thread.start()


def run_command(command):
    # trim the newline
    command = command.rstrip()

    # run the command and get the output back
    try:
        with open(os.devnull, 'w') as devnull:
            output = subprocess.check_output(command, 
   stderr=subprocess.STDOUT, shell=True)
    except:
        output = "Failed to execite command. \r\n"

    # send the output back to the client
    return output


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

    # check for upload
    if len(upload_destination):

        # read in all of the bytes and write to out destination
        file_line = ""

        # keep reading data until none is available
        while True:
            data = client_socket.recv(1024)

            if not data:
                break
            else:
                file_line += data

        # now we take these bytes and try to write them out
        try:
            file_descriptor = open(upload_destination, "wb")
            file_descriptor.write(file_line)
            file_descriptor.close()

            # acknowledge that we wrote the file out
            client_socket.send("Succesfully saved file to %s\r\n" % 
   upload_destination)
        except:
            client_socket.send("Failed to save file to %s\r\n" % 
   upload_destination)

    # check for command execution
    if len(execute):
        # run the command
        output = run_command(execute)

        client_socket.send(output)


    # now we go into another loop if a command shell was requested
    if command:

        while True:
            # show a simple prompt
            client_socket.send("<BHP:#> ")

            # now we receive until we see a linefeed (enter key)
            cmd_line = ""
            while "\n" not in cmd_line:
                cmd_line += client_socket.recv(1024)

            # send back the command output
            response = run_command(cmd_line)

            # send back the response
            client_socket.send(response)
            main()
导入系统 导入套接字 导入getopt 导入线程 导入子流程 导入操作系统 #定义全局变量 听=假 命令=False 上传=错误 execute=“” target=“” upload_destination=“” 端口=0 def用法(): 打印“必和必拓网络工具” 打印“用法:netcat2.py-t目标\u主机-p端口” 打印“-l--侦听-在[host]:[port]上侦听传入的 “联系” print“-e--execute=file_to_run-在收到文件后执行给定文件 “联系” 打印“-c--命令-初始化命令外壳” 打印“-u--上传=目的地-收到连接后上传 文件并连接到[目的地]” 打印“示例:” 打印“netcat2.py-t192.168.0.1-p5555-l-c” 打印“netcat2.py-t192.168.0.1-p5555-l-u=C:\\target.exe” 打印“netcat2.py-t192.168.0.1-p5555-l-e=\“cat/etc/passwd” 打印“echo'ABCDEFGHI'|/netcat2.py-t 192.168.0.1-p 135” 系统出口(0) def main(): 全球倾听 全球港口 全局执行 全局命令 全球上传目的地 全球目标 如果不是len(sys.argv[1:]): 用法() #阅读命令行选项 尝试: opts,args=getopt.getopt(sys.argv[1:],“hle:t:p:cu”,[“help”, “侦听”、“执行”、“目标”、“端口”、“命令”、“上载”]) 除getopt.GetOpError作为错误外: 打印str(错误) 用法() 对于o,a在选项中: 如果o在(“-h”中,“--help”): 用法() 以利夫o在(“-l”,“听”): 倾听=正确 如果在(“-e”,“执行”): 执行=a elif o in(“-c”,“--commandshell”): 命令=True elif o in(“-u”,“--upload”): 上传目的地=a 如果在(“-t”,“目标”)中出现以下情况: 目标=a 在(“-p”和“--port”)中的elif o: 端口=int(a) 其他: assert False,“未处理的选项” #我们是要监听还是只是从标准数据网发送数据? 如果不侦听且len(目标)和端口>0: #从命令行中读入该行 #这将阻塞,因此如果不发送输入,请发送CTRL-D #标准 line=sys.stdin.readline() 打印(行) #发送数据 客户端\发送方(行) #我们将倾听并潜在地 #上传东西,执行命令,然后放回shell #取决于上面的命令行选项 如果听: 服务器_循环() def客户端_发送器(第行): client=socket.socket(socket.AF\u INET,socket.SOCK\u流) 尝试: #连接到我们的目标主机 client.connect((目标,端口)) 如果len(行): client.send(行) 尽管如此: #现在等待数据返回 记录长度=1 response=“” 而recv_len: data=client.recv(4096) 记录长度=长度(数据) 响应+=数据 如果记录长度<4096: 打破 打印“回复” #等待更多的输入 行=原始输入(“”) 行+=“\n” #送走 client.sendline() 除: 打印“[*]异常!正在退出。” #断开连接 client.close() def服务器_循环(): 全球目标 #如果没有定义目标,我们将侦听所有接口 如果不是len(目标): target=“0.0.0.0” 服务器=socket.socket(socket.AF\u INET,socket.SOCK\u流) 绑定((目标,端口)) 服务器。听(5) 尽管如此: client_socket,addr=server.accept() #剥离线程以处理新客户机 client\u thread=threading.thread(target=client\u handler,args= (客户端_套接字,)) client_thread.start() def run_命令(命令): #修剪新线 command=command.rstrip() #运行该命令并返回输出 尝试: 将open(os.devnull,'w')作为devnull: 输出=子进程。检查输出(命令, stderr=subprocess.STDOUT,shell=True) 除: output=“执行命令失败。\r\n” #将输出发送回客户端 返回输出 def客户端处理程序(客户端套接字): 全球上传 全局执行 全局命令 #检查上传 如果len(上传目的地): #读入所有字节并写入目标 file_line=“” #继续读取数据,直到没有可用数据 尽管如此: data=client_socket.recv(1024) 如果没有数据: 打破 其他: 文件行+=数据 #现在我们把这些字节写出来 尝试: 文件\描述符=打开(上传\目标,“wb”) 文件\描述符.write(文件\行) 文件\u描述符.close() #确认我们写了文件 客户端\u套接字.send(“已成功将文件保存到%s\r\n”% 上传(目的地) 除: 客户端\u套接字.send(“未能将文件保存到%s\r\n”% 上传(目的地) #检查命令执行情况 如果len(执行): #运行命令 输出=运行_命令(执行) 客户端\u套接字发送(输出) #现在,如果请求了命令shell,我们将进入另一个循环 如果命令: 尽管如此: #显示一个简单的提示 客户端\u套接字发送(“”) #现在我们接收,直到看到换行符(输入键) cmd_line=“” 当“\n”不在命令行中时: cmd_line+=client_socket.recv(1024) #发回命令输出 响应=r
<BHP:#> Failed to execite command. 
<BHP:#>