python 模拟netcat

学习记录:

1.当一条命令用续行符 (“\”) 分割成多行时, 后续的行可以以任何方式缩近, 此时 Python 通常的严格的缩近规则无需遵守。严格地讲, 在小括号, 方括号或大括号中的表达式 (如 定义一个 dictionary) 可以用或者不用续行符 (“\”) 分割成多行。


2.python getopt使用
http://blog.csdn.net/tianzhu123/article/details/7655499


3.socket bind

python socket bind 可以指定IP, 但如果socket.bind(("192.168.22.112",8099)), 这样的话,127.0.0.1:8099, 或者localhost:8099都无法访问,

bash-3.2# telnet 127.0.0.1 8099
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused

bind 0.0.0.0就可以绑定这机器上的所有IP



4.多线程
https://www.cnblogs.com/fnng/p/3670789.html


5 subprocess库 提供了强大的进程创建接口,可以提供给你多种与客户端程序交互的方法。


6.python3 中 socket.send() 不能传输String   要string.encode("utf-8"),接收时要 decode("utf-8")



代码 

import sys
import socket
import getopt  # 命令行参数
import threading
import subprocess  # subprocess通过子进程来执行外部指令,并通过input/output/error管道,获取子进程的执行的返回信息。

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


def usage():
    print("BHP Net Tool")
    print()
    print("Usage:netcat.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 inpon \
                                                receiving a command shell")
    print("-c command               - initialize a command shell")
    print("-u --upload=destination - upon receiving connection upload a \
                                    file and write to [destination]")
    print()
    print()
    print("Examples: ")
    print("netcat.py -t 192.168.0.1 -p 5555 -l -c")
    print("netcat.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe")
    print("netcat.py -t 192.168.0.1 -p 5555 -l -e='cat /etc/passwd'")
    print("echo 'ABCDEFGHI'| ./netcat.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:
        # 从命令行读取内存数据
        print("请输入")
        buffer = sys.stdin.read()
        # 发送数据
        client_sender(buffer)

    # 我们开始监听 并准备上传文件、执行命令
    if listen:
        server_loop()



def client_sender(buffer):
    global target
    global port
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

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

        if len(buffer):
            client.send(buffer.encode("utf-8"))

        while True:
            recv_len = 1
            response = ""
            while recv_len:
                data = client.recv(4096).decode("utf-8")
                recv_len = len(data)
                response += data
                if recv_len < 4096:
                    break
            print(response)

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

            client.send(buffer)
    except Exception as e:
        print(e)
        client.close()


def server_loop():
    global target
    global port

    # 没有目标,监听所有端口
    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:
        print("开始监听")
        client_socket, addr = server.accept()
        print("来了")
        # 分拆一个线程去处理
        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 {}".format(upload_destination))
        except:
            client_socket.send("Faile to save file to {}".format(upload_destination))

    if len(execute):
        output = run_command(execute)

        client_socket.send(output)

    if command:

        while True:

            client_socket.send(" ".encode("utf-8"))
            cmd_buffer = ""
            while "\n" not in cmd_buffer:
                cmd_buffer += client_socket.recv(1024).decode("utf-8")
            response = run_command(cmd_buffer)
            client_socket.send(response)

main()


你可能感兴趣的:(python)