-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
311 lines (252 loc) · 10.1 KB
/
server.py
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
#importing required modules
import socket
import sys
import subprocess
import os
import time
import psutil
import platform
from datetime import datetime
import cpuinfo
import socket
import threading
from multiprocessing import Pool
# pip install psutil
# pip install py-cpuinfo
#create a socket
def create_socket():
try:
#global variable so that we can access these variables in other functions
global host
global port
global s
host=''
port=9999
s = socket.socket()
except socket.error as error_messsage:
print("Error creating socket: " + str(error_messsage))
sys.exit()
#bind the socket to the port and listening for connections
def bind_socket():
try:
global host
global port
global s
print("Binding the port: " + str(port))
s.bind((host,port))
s.listen(5) #listen for 5 connections at once (max)
except socket.error as error_messsage:
print("Error binding the port: " + str(error_messsage) + "\n" + "Retrying...")
bind_socket() #call the function again to try binding again
#accept a connection with a server when socket is listening
def accept_connection():
while (1):
connection, address = s.accept()
print("Connection has been established! | " + "IP " + address[0] + " | Port " + str(address[1]))
currentWD = os.getcwd() + "> "
connection.send(str.encode( currentWD)) # send cwd
create_thread_for_process(connection)
#creating thread of each client
def create_thread_for_process(connection):
#each thread will start a new process for each client(i.e for each client 1 process and 1 thread)
thread = threading.Thread(target=create_process_for_client,args=([connection]))
thread.daemon = True
thread.start()
#
def create_process_for_client(connection):
#every new connection will start a new thread which will start a new process
#new process cause change directory requires new process not new thread for each client
pool = Pool(maxtasksperchild=2)
pool.map(check_commands, [connection])
pool.close()
pool.join()
#execute commands sent by the server
def check_commands(connection):
while(True):
data = connection.recv(1024)
data = data.decode('utf-8')
if "send" in ''.join(data[:5]).lower():
receive_file_from_client(data,connection)
elif "receive" in ''.join(data[:9]).lower():
send_file_to_client(data,connection)
elif "sysinfo" in ''.join(data[:9]).lower():
send_syteminfo_from_server(data,connection)
elif "exit" in ''.join(data[:5]).lower():
print("Closing connection ...")
#print("Closed")
connection.close()
sys.exit()
break
else:
execute_command(data,connection)
# send system information to client
def send_syteminfo_from_server(command,connection):
# convert given bytes into proper format
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{bytes:.2f}{unit}{suffix}"
bytes /= factor
info = ''
info+="="*40+ "System Information"+ "="*40+"\n"
uname = platform.uname()
info+=f"System: {uname.system}"+"\n"
info+=f"Node Name: {uname.node}"+"\n"
info+=f"Release: {uname.release}"+"\n"
info+=f"Version: {uname.version}"+"\n"
info+=f"Machine: {uname.machine}"+"\n"
info+=f"Processor: {uname.processor}"+"\n"
info+=f"Processor: {cpuinfo.get_cpu_info()['brand_raw']}"+"\n"
info+=f"Ip-Address: {socket.gethostbyname(socket.gethostname())}"+"\n"
#info+=f"Mac-Address: {':'.join(re.findall('..', '%012x' % uuid.getnode()))}"+"\n"
# Boot Time
info+="="*40+ "Boot Time"+ "="*40 +"\n"
boot_time_timestamp = psutil.boot_time()
bt = datetime.fromtimestamp(boot_time_timestamp)
info+=f"Boot Time: {bt.year}/{bt.month}/{bt.day} {bt.hour}:{bt.minute}:{bt.second}"+"\n"
# print CPU information
info+="="*40+ "CPU Info"+ "="*40 +"\n"
# number of cores
info+=f"Physical cores: {psutil.cpu_count(logical=False)}" +"\n"
info+=f"Total cores: {psutil.cpu_count(logical=True)}" +"\n"
# CPU frequencies
cpufreq = psutil.cpu_freq()
info+=f"Max Frequency: {cpufreq.max:.2f}Mhz"+"\n"
info+=f"Min Frequency: {cpufreq.min:.2f}Mhz"+"\n"
info+=f"Current Frequency: {cpufreq.current:.2f}Mhz"+"\n"
# CPU usage
info+="CPU Usage Per Core:"+"\n"
for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
info+=f"Core {i}: {percentage}%"+"\n"
info+=f"Total CPU Usage: {psutil.cpu_percent()}%"+"\n"
# Memory Information
info+="="*40+ "Memory Information"+ "="*40 +"\n"
# get the memory details
svmem = psutil.virtual_memory()
info+=f"Total: {get_size(svmem.total)}"+"\n"
info+=f"Available: {get_size(svmem.available)}"+"\n"
info+=f"Used: {get_size(svmem.used)}"+"\n"
info+=f"Percentage: {svmem.percent}%"+"\n"
info+="="*20+ "SWAP"+ "="*20 +"\n"
# get the swap memory details (if exists)
swap = psutil.swap_memory()
info+=f"Total: {get_size(swap.total)}"+"\n"
info+=f"Free: {get_size(swap.free)}"+"\n"
info+=f"Used: {get_size(swap.used)}"+"\n"
info+=f"Percentage: {swap.percent}%"+"\n"
# Disk Information
info+="="*40+ "Disk Information"+ "="*40 +"\n"
info+="Partitions and Usage:"+"\n"
# get all disk partitions
partitions = psutil.disk_partitions()
for partition in partitions:
info+=f"=== Device: {partition.device} ==="+"\n"
info+=f" Mountpoint: {partition.mountpoint}"+"\n"
info+=f" File system type: {partition.fstype}"+"\n"
try:
partition_usage = psutil.disk_usage(partition.mountpoint)
except PermissionError:
# this can be catched due to the disk that
# isn't ready
continue
info+=f" Total Size: {get_size(partition_usage.total)}"+"\n"
info+=f" Used: {get_size(partition_usage.used)}"+"\n"
info+=f" Free: {get_size(partition_usage.free)}"+"\n"
info+=f" Percentage: {partition_usage.percent}%"+"\n"
# get IO statistics since boot
disk_io = psutil.disk_io_counters()
info+=f"Total read since boot: {get_size(disk_io.read_bytes)}"+"\n"
info+=f"Total write since boot: {get_size(disk_io.write_bytes)}"+"\n"
##get IO statistics since boot
info+="="*40+ "IO statistics since boot"+ "="*40 +"\n"
net_io = psutil.net_io_counters()
info+=f"Total Bytes Sent: {get_size(net_io.bytes_sent)}"+"\n"
info+=f"Total Bytes Received: {get_size(net_io.bytes_recv)}"+"\n"
connection.send(str.encode(info))
return None
#execute command received by the client
def execute_command(command,connection):
if command.lower()=="close":
connection.close()
if command[:2] == 'cd':
os.chdir(os.path.abspath(command[3:]))
output_str = "Command Exectuted Successfully." + '\n'
currentWD = os.getcwd() + "> "
connection.send(str.encode( currentWD + output_str ))
elif len(command) > 0:
cmd = subprocess.Popen(command[:],shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
output_byte = cmd.stdout.read() + cmd.stderr.read() # output and error messages
output_str = str(output_byte,"utf-8") or "Command Exectuted Successfully."
currentWD = os.getcwd() + "> "
connection.send(str.encode( currentWD + output_str ))
#print(output_str)
check_commands(connection)
#send file to client that is asked to received
def send_file_to_client(command,connection):
file_info_list = command.strip(' ') # remove trailing spaces
file_info_list = list(map(str,file_info_list.split()))
file_path = file_info_list[1] # 0th element is the command, 1st element is the file path
if os.path.isfile(file_path):
file_size = os.path.getsize(file_path)
connection.send(str.encode(str(file_size)))
time.sleep(0.3)
# Opening file and sending data.
with open(file_path, "rb") as file:
c = 0
# Starting the time capture.
start_time = time.time()
# Running loop while c != file_size.
print("Sending file...")
while c <= file_size:
data = file.read(1024)
if not (data):
break
connection.sendall(data)
c += len(data)
# Ending the time capture.
end_time = time.time()
print("File succesfully sended to client. Total time to transfer: ", end_time - start_time)
else:
print ("File path does not exist")
connection.send(str.encode("0"))
return None
#receive file from client
def receive_file_from_client(command,connection):
file_info_list = command.strip(' ') # remove trailing spaces
file_info_list = list(map(str,file_info_list.split()))
if len(file_info_list) == 2:
file_name="temp_file.txt"
else:
file_name = file_info_list[2] # 0th element is the command, 2nd element is the file name
file_path = "./res/" + file_name
os.makedirs(os.path.dirname(file_path), exist_ok=True)
# Getting file details.
file_size = connection.recv(100).decode()
# Opening and reading file.
with open( file_path, "wb") as file:
c = 0
# Starting the time capture.
print("Receiving file...")
start_time = time.time()
# Running the loop while file is recieved.
while c < int(file_size):
data = connection.recv(1024)
file.write(data)
c += len(data)
# Ending the time capture.
end_time = time.time()
print("File received from client. Total time: ", end_time - start_time)
return None
def main():
create_socket()
bind_socket()
accept_connection()
if __name__ == '__main__':
main()