-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpycafeclient.py
More file actions
168 lines (145 loc) · 5.7 KB
/
pycafeclient.py
File metadata and controls
168 lines (145 loc) · 5.7 KB
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
import random
import re
import socket
import subprocess
import threading
import time
import sys
import datetime
# Define the IP address and port where the script will listen
HOST = '0.0.0.0' # Listen on all network interfaces
PORT = 22077
CLOCK_PORT = 22177
LOCKER_PORT = 22277
# text file to redirect the output of the script, None to disable
output_file = f"C:\\PyCafe\\Logs\\pycafeclient\\pycafeclient_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.log"
sys.stdout = open(output_file, "w") if output_file is not None else sys.__stdout__
sys.stderr = sys.stdout
logs_flushing_rate = 30 # in seconds
session_timer = 0 # in seconds
session_timer_update_rate = 60 # in seconds
clock_update_rate = 30 # in seconds
def lock_pc():
send_command("localhost", LOCKER_PORT, "lock", False, False)
def change_password(new_password):
try:
# Get the list of users from the system
result = subprocess.run('net user', shell=True, capture_output=True, text=True)
# get the user PC-<index>-Guest using regex
pattern = re.compile(r"PC-\d+-Guest")
username = None
for line in result.stdout.splitlines():
for user in line.split():
match = pattern.match(user)
if match:
username = match.group()
break
if username is None:
print("Error: user not found.")
return
# Command to change the user password
command = f'net user "{username}" {new_password}'
# Run the command using subprocess
result = subprocess.run(command, shell=True, capture_output=True, text=True)
# Check if the command was successful
if result.returncode == 0:
print(f"Password for {username} successfully changed.")
else:
print(f"Error changing password: {result.stderr}")
except Exception as e:
print(f"An error occurred: {e}")
def ping(conn, adress):
print('got pinged by ' + str(adress))
# ping the locker script
if not send_command("localhost", LOCKER_PORT, "ping", receive_response=True, silent_fail=True) == "pong":
print("locker dead")
conn.sendall("locker dead".encode('utf-8'))
return
conn.sendall("pong".encode('utf-8'))
def restart_pc():
# Use Windows API to restart the PC
subprocess.run("shutdown /r /t 0", shell=True)
print("PC Restarting")
def set_session_timer(seconds):
global session_timer
session_timer = seconds
def send_session_timer(conn):
conn.sendall(str(session_timer).encode('utf-8'))
def handle_client_connection(args):
conn, adress = args[0], args[1]
with conn:
command = conn.recv(1024).decode('utf-8')
print(f"Received command: {command}")
if command.startswith("ping"):
ping(conn, adress)
elif command.startswith("lock"):
cmd_args = command.split(" ")
if len(cmd_args) == 2:
change_password(cmd_args[1])
lock_pc()
else:
lock_pc()
elif command.startswith("restart"):
restart_pc()
elif command.startswith("change_password"):
cmd_args = command.split(" ")
change_password(cmd_args[1])
elif command.startswith("set_timer"):
cmd_args = command.split(" ")
if len(cmd_args) == 2:
set_session_timer(int(cmd_args[1]))
elif command.startswith("get_timer"):
send_session_timer(conn)
else:
print("Invalid command received.")
# session timer thread
def update_session_timer():
global session_timer
while True:
# Decrement the session timer
session_timer = max(0, session_timer - session_timer_update_rate)
time.sleep(session_timer_update_rate)
# client clock thread
def update_client_clock():
while True:
send_command("localhost", CLOCK_PORT, f"set_timer {session_timer}", silent_fail=True)
time.sleep(clock_update_rate)
# log flushing thread
def update_flush_logs():
while True:
sys.stdout.flush()
time.sleep(logs_flushing_rate)
def listen_for_connections():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
print(f"Listening on {HOST}:{PORT}")
while True:
conn, addr = s.accept()
args = (conn, addr)
threading.Thread(target=handle_client_connection, args={args}, daemon=True).start()
def send_command(ip, port, command, receive_response=False, silent_fail=False):
for i in range(2):
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(2)
s.connect((ip, port))
s.sendall(command.encode('utf-8'))
print(f"Sent command: {command}")
return s.recv(1024).decode('utf-8') if receive_response else True
except Exception as e:
if not silent_fail:
print(f"Error sending command to {ip}: {command}\nError: {e}\nAttempt {i+1}")
return None if receive_response else False
if __name__ == "__main__":
# Start the PC with a random password
change_password(random.randint(1000, 9999))
lock_pc()
# Start the session timer in a separate thread
threading.Thread(target=update_session_timer, daemon=True).start()
# Start the client clock update in a separate thread
threading.Thread(target=update_client_clock, daemon=True).start()
# Start the log flushing in a separate thread
threading.Thread(target=update_flush_logs, daemon=True).start()
# Start listening for connections in the main thread
listen_for_connections()