PYTHON 黑帽子第二章总结

  基于python3编写

import sys, socket, getopt, threading, argparse, subprocess

# globals options
listen = False
command = False
upload = None
execute = None
target = None
upload_destination = None
port = None


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

    # set up argument parsing
    parser = argparse.ArgumentParser(description="netcat clone")
    parser.add_argument("-p","--port", type=int, help="target port")
    parser.add_argument("-t", "--target_host", type=str, help="target host", default="0.0.0.0")
    parser.add_argument("-l", "--listen", help="listen on [host]:[port} for incomming connections", action="store_true",default=False)  # action 有参数为true,没有参数default false
    parser.add_argument("-e", "--execute", help="execute file-to-run execute the given file upn receiving a connection")
    parser.add_argument("-c", "--command", help="initialize a command shell", action="store_true", default=False)
    parser.add_argument("-u", "--upload",help="--upload=destination upon receing connection upload and write to destination")
    args = parser.parse_args()

    # parse arguments
    target = args.target_host
    port = args.port
    listen = args.listen
    execute = args.execute
    command = args.command
    upload_destination = args.upload

    # if listen is false and send send data from stdin
    if not listen and target is not None and port > 0:
        print("DBG:read data from stdin")
        # read buffer from stdin , this will block so send CTRL-D if not
        # sending to stdin 从stdin发送
        buff = sys.stdin.read()


        print("Sending {0} to client".format(buff))
        # send data
        client_sender(buff)

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


def client_sender(buff):
    print("DBG:sending data to client on port" + str(port))

    # create a sockets
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

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

        if len(buff):
            client.send(buff.encode())
        while True:
            # now let's wait for data response
            recv_len = 1
            response = ""

            while recv_len:
                print("DBG:waiting for response from client")
                data = client.recv(4096)
                recv_len = len(data)
                response += data.decode(errors="ignore")

                if recv_len < 4096:
                    break
            # end=""  statement does not end
            print(response, end="")

            # wait for more input
            buff = input("")
            buff += "\n"
            # send it off
            client.send(buff.encode())
    except:
        print("[*] Exception! Exiting.")
    finally:
        client.close()


def server_loop():
    global target
    print("DBG:entering server loop")

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

    server.listen(5)

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

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


def run_command(command):
    # trim the newline rstrip trim the end of newline
    command = command.rstrip()
    print("DGB:executing command:" + command)

    try:
        # this will launch a new process ,note:cd commands are useless
        output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
    except:
        output = "Failed to execute to command.\r\n"

    # send the output back to the client
    return output


# 服务端监听,获取从客户端发来的数据执行命令
def client_handler(client_socket):
    global upload
    global execute
    global command
    print("DBG:handling client socket")

    # check for upload
    if upload_destination is not None:
        print("DEBG:entering file upload")

        # read all of the bytes and write them to the destination
        file_buff = ""

        # keep reading data until none is available
        while True:
            data = client_socket.recv(1024)
            if not data:
                break
            else:
                file_buff += data.decode()

        # write bytes to file
        try:
            f = open(upload_destination, "wb")
            f.write(file_buff)
            f.close()

            # ACK file writing
            client_socket.send("Successfully saved file to {0}\r\n".format(upload_destination).encode())
        except:
            client_socket.send("Failed to save file to {0}\r\n".format(upload_destination).encode())

    if execute is not None:
        print("DBG: going to execute command")

        # run the command
        output = run_command(execute)
        client_socket.send(output.encode())

    # go into loop if a command shell was resquested
    if command:
        print("DBG:shell requested")

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

            # now recieve until linefeed
            cmd_buff = ""
            while "\n" not in cmd_buff:
                cmd_buff += client_socket.recv(1024).decode()

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

            # 判断一个response是否为str类型
            if isinstance(response, str):
                response = response.encode()

            # send back the response
            client_socket.send(response + "<BHP:#>".encode())


if __name__ == '__main__':
    main()

  使用实列:

服务端执行:

python necat_1.py -l -p 9999 -c

客户端执行:

python nccat_1.py -t localhost -p 9999

 

客户端执行需要EOF读取结束,linux(ctrl-d),windows(ctrl-z)

 

转载于:https://www.cnblogs.com/junsec/p/10828255.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值