asteroidsteam icon

RC Script

asteroidsteam | PRO | 02/02/20 06:05:17 AM UTC | 0 ⭐ | 427 👁️ | Never ⏰ | []
Python |

2.76 KB

|

None

|

0 👍

/

0 👎

import socket
import threading
import subprocess
 
HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 1234        # Port to listen on (non-privileged ports are > 1023)
 
def exec(cmd, sSock):
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    for line in iter(process.stdout.readline, b''):
        sSock.write('   '+line.decode())
        
# START COMMAND DEFINITION #
 
def help(args, sSock):
    sSock.print("""Command : Description : Arguments - [] = optional, <> = required
    help : Display's this menu         : [command]
    bash : Remotely run a bash command : <command> [opt args]
    say  : Make computer say something : <message>""")
 
def bash(args, sSock):
    if (len(args) < 1):
        sSock.print("Usage: bash <command> [opt args]")
        return
    sSock.print("Executing command: {}...\n".format(' '.join(args)))
    exec(args, sSock)
    sSock.print("\nExecution Completed.")
 
def say(args, sSock):
    if (len(args) < 1):
        sSock.print("Usage: say <message>")
        return
    message = ' '.join(args)
    sSock.print("Saying: {}".format(message))
    exec(['say', message], sSock)
    sSock.print("Execution Completed.")
 
commands = {
    'help': help,
    'bash': bash,
    'say': say
}
 
# END COMMAND DEFINITION #
 
def recvall(sock):
    BUFF_SIZE = 4096 # 4 KiB
    data = b''
    while True:
        part = sock.recv(BUFF_SIZE)
        data += part
        if len(part) < BUFF_SIZE:
            # either 0 or end of data
            break
    return data
 
class sFunc():
    def __init__(
        self,
        conn
    ):
        self.conn = conn
    def sbytes(self,str):
        return str.encode()
    def print(self,str):
        str += '\n'
        self.conn.sendall(self.sbytes(str))
    def write(self,str):
        self.conn.sendall(self.sbytes(str))
    def input(self,prompt):
        self.write(prompt)
        ret = recvall(self.conn)
        return ret.decode()
 
def processCommand(cmd, args, sSock):
    if cmd in commands:
        commands[cmd](args, sSock)
    else:
        sSock.print("Unknown Command: {}, type help for help.".format(cmd))
 
def clientThread(conn, addr):
    sSock = sFunc(conn)
    while True:
        command = sSock.input("Enter a command: ").rstrip()
        args = command.split(' ')[1:]
        command = command.split(' ')[0]
        processCommand(command,args,sSock)
 
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    s.listen()
    while True:
        conn, addr = s.accept()
        threading.Thread(
            target=clientThread,
            args=[conn,addr],
            daemon=True
        ).start()

Comments