#!/usr/bin/env python3 from socket import * from _thread import start_new_thread from struct import pack, unpack from time import sleep from subprocess import getoutput our_socket = socket(AF_INET, SOCK_STREAM) our_socket.bind(("0.0.0.0", 5080)) our_socket.listen(5) # Protocol: # From the client # ADDMON = 1, DELMON = 2 # Username length is 1 byte # Actual username # From the server # username length (1 byte) # username # message length (2 bytes) # message # ADDMON = 1 DELMON = 2 monitored_users = [] current_clients = [] # The already_reported syste is broken, sorry! already_reported = [] def send_result(username, result): if (username, result) in already_reported: return already_reported.append((username, result)) for cs in current_clients: # Later: add try and except print("Sending " + result + " to ", cs) cs.send(pack(">B", len(username))) cs.send(username.encode("utf-8")) cs.send(pack(">H", len(result))) cs.send(result.encode("utf-8")) def monitor(): while True: sleep(1) # Put whatever monitoring code you want here! for u in monitored_users: pyresult = getoutput("ps axu | grep " + u + " | grep python | grep -v ^`whoami`") # For the future: Don't send it if we already did if(len(pyresult) > 0): # send it out send_result(u, pyresult) # And so on with anything we want to monitor start_new_thread(monitor, ()) def handle_client(client_socket): current_clients.append(client_socket) while True: try: opcode = unpack(">B", client_socket.recv(1, MSG_WAITALL))[0] print("Got opcode: ", opcode) if(opcode == ADDMON): uname_len = unpack(">B", client_socket.recv(1))[0] username = client_socket.recv(uname_len, MSG_WAITALL).decode("utf-8") monitored_users.append(username) elif(opcode == DELMON): uname_len = unpack(">B", client_socket.recv(1))[0] username = client_socket.recv(uname_len, MSG_WAITALL).decode("utf-8") monitored_users.remove(username) else: # Not part of the protocol break print("Monitored Users: ", monitored_users) except: print("Something is wrong with that client") break current_clients.remove(client_socket) client_socket.close() while True: client_socket, client_address = our_socket.accept() print("We got a new connection from: ", client_address[0], client_address[1]) start_new_thread(handle_client, (client_socket, )) our_socket.close()