#!/usr/bin/env python3 from socket import * from _thread import start_new_thread from subprocess import getoutput from struct import * # Protocol: # Opcode 1: usercount # Opcode 2: uptime # Opcode 255: disconnect # Either way, the server sends a 2-byte response # Create a socket, open it, and get ready for connections our_socket = socket(AF_INET, SOCK_STREAM) our_socket.bind(("0.0.0.0", 5105)) our_socket.listen(5) # This function will be running once per client def handle_client(cskt): while True: try: opcode = unpack(">B", cskt.recv(1))[0] except: break print("received opcode", opcode) if opcode == 1: usercount = int(getoutput('who | sed "s/ .*//g" | sort -u | wc -l')) usercount_encoded = pack(">H", usercount) cskt.send(usercount_encoded) # This is 2 bytes elif opcode == 2: uptime = int(getoutput('uptime | grep -o " [0-9]* days" | sed s/days//g')) uptime_encoded = pack(">H", uptime) cskt.send(uptime_encoded) # This is also 2 bytes else: # Another option: if opcode not in [1, 2]: break print("Done with client on socket ", cskt) cskt.close() # This loop runs one iteration per new connection while True: client_socket, client_address = our_socket.accept() start_new_thread(handle_client, (client_socket, )) print("We got a new connection from: ", client_address[0], client_address[1]) our_socket.close()