5
5
import hashlib
6
6
import logging
7
7
8
- UPLOAD_DIR = os .path .join ('uploads' ) # Directory to save uploaded files
8
+ UPLOAD_DIR = os .path .join ('uploads' )
9
+ BUFFER_SIZE = 1024
9
10
10
- # Setup logging
11
11
logging .basicConfig (level = logging .INFO , format = '%(asctime)s - %(levelname)s - %(message)s' )
12
12
13
- if not os .path .exists (UPLOAD_DIR ):
14
- os .makedirs (UPLOAD_DIR )
13
+ os .makedirs (UPLOAD_DIR , exist_ok = True )
15
14
16
15
def calculate_checksum (file_path ):
17
16
"""Calculate SHA-256 checksum of a file for integrity check."""
@@ -26,69 +25,80 @@ def safe_path(base_dir, file_name):
26
25
return os .path .join (base_dir , os .path .basename (file_name ))
27
26
28
27
def handle_client (client_socket ):
28
+ """Handle commands from the client."""
29
29
try :
30
30
while True :
31
- command = client_socket .recv (1024 ).decode ()
31
+ command = client_socket .recv (BUFFER_SIZE ).decode (). strip ()
32
32
if not command :
33
33
break
34
34
35
35
logging .info (f"Received command: { command } " )
36
-
37
- if command .lower () == 'ping' :
38
- client_socket .send (b'Running' )
36
+ response = handle_command (command , client_socket )
39
37
40
- elif command .lower () == 'exit' :
41
- client_socket .send (b'Connection closing' )
42
- break
38
+ client_socket .send (response .encode ())
43
39
44
- elif command .lower ().startswith ('upload ' ):
45
- try :
46
- file_name = safe_path (UPLOAD_DIR , command [7 :])
47
- file_size = int (client_socket .recv (1024 ).decode ())
48
- client_socket .send (b'Ready to receive file' )
49
-
50
- # File upload process
51
- with open (file_name , 'wb' ) as f :
52
- received = 0
53
- while received < file_size :
54
- data = client_socket .recv (min (file_size - received , 1024 ))
55
- if not data :
56
- break
57
- f .write (data )
58
- received += len (data )
59
-
60
- client_socket .send (b'File uploaded' )
61
-
62
- # Verify file integrity
63
- checksum = calculate_checksum (file_name )
64
- client_socket .send (f'Checksum: { checksum } ' .encode ())
65
-
66
- except Exception as e :
67
- logging .error (f"Upload failed: { e } " )
68
- client_socket .send (f'Upload failed: { str (e )} ' .encode ())
69
-
70
- elif command .lower ().startswith ('exec ' ):
71
- file_to_run = safe_path (UPLOAD_DIR , command [5 :])
72
- if os .path .isfile (file_to_run ):
73
- try :
74
- subprocess .Popen (file_to_run , shell = True )
75
- client_socket .send (b'Execution started' )
76
- logging .info (f"Execution started for { file_to_run } " )
77
- except Exception as e :
78
- logging .error (f"Execution failed: { e } " )
79
- client_socket .send (f'Execution failed: { str (e )} ' .encode ())
80
- else :
81
- client_socket .send (b'File not found' )
82
-
83
40
except Exception as e :
84
41
logging .error (f"Client handling error: { e } " )
85
42
finally :
86
43
client_socket .close ()
87
44
logging .info ("Connection closed" )
88
45
46
+ def handle_command (command , client_socket ):
47
+ """Process commands from the client."""
48
+ if command .lower () == 'ping' :
49
+ return 'Running'
50
+
51
+ elif command .lower () == 'exit' :
52
+ return 'Connection closing'
53
+
54
+ elif command .lower ().startswith ('upload ' ):
55
+ return handle_upload (command [7 :], client_socket )
56
+
57
+ elif command .lower ().startswith ('exec ' ):
58
+ return handle_exec (command [5 :])
59
+
60
+ return 'Unknown command'
61
+
62
+ def handle_upload (file_name , client_socket ):
63
+ """Handle file upload from the client."""
64
+ try :
65
+ file_path = safe_path (UPLOAD_DIR , file_name )
66
+ file_size = int (client_socket .recv (BUFFER_SIZE ).decode ())
67
+ client_socket .send (b'Ready to receive file' )
68
+
69
+ with open (file_path , 'wb' ) as f :
70
+ received = 0
71
+ while received < file_size :
72
+ data = client_socket .recv (min (file_size - received , BUFFER_SIZE ))
73
+ if not data :
74
+ break
75
+ f .write (data )
76
+ received += len (data )
77
+
78
+ logging .info (f'File uploaded: { file_path } ' )
79
+ checksum = calculate_checksum (file_path )
80
+ return f'File uploaded. Checksum: { checksum } '
81
+
82
+ except Exception as e :
83
+ logging .error (f"Upload failed: { e } " )
84
+ return f'Upload failed: { str (e )} '
85
+
86
+ def handle_exec (file_name ):
87
+ """Execute a file if it exists."""
88
+ file_path = safe_path (UPLOAD_DIR , file_name )
89
+ if os .path .isfile (file_path ):
90
+ try :
91
+ subprocess .Popen (file_path , shell = True )
92
+ logging .info (f"Execution started for { file_path } " )
93
+ return 'Execution started'
94
+ except Exception as e :
95
+ logging .error (f"Execution failed: { e } " )
96
+ return f'Execution failed: { str (e )} '
97
+ return 'File not found'
98
+
89
99
def main ():
90
100
server = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
91
- server .setsockopt (socket .SOL_SOCKET , socket .SO_REUSEADDR , 1 ) # To reuse the socket address
101
+ server .setsockopt (socket .SOL_SOCKET , socket .SO_REUSEADDR , 1 )
92
102
server .bind (('0.0.0.0' , 9999 ))
93
103
server .listen (5 )
94
104
logging .info ('Listening on port 9999' )
@@ -97,11 +107,11 @@ def main():
97
107
while True :
98
108
client_socket , addr = server .accept ()
99
109
logging .info (f'Accepted connection from { addr } ' )
100
- client_socket .settimeout (60 ) # Set a timeout for client socket
110
+ client_socket .settimeout (60 )
101
111
client_handler = threading .Thread (target = handle_client , args = (client_socket ,))
102
112
client_handler .start ()
103
113
except Exception as e :
104
- logging .error (f"Server error: { e } " )
114
+ logging .error (f"Server error: {e ")
105
115
finally :
106
116
server .close ()
107
117
0 commit comments