Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import re
- import asyncore
- import traceback
- import subprocess
- from socket import AF_INET, SOCK_STREAM
- class WinCLI:
- default_prompt = re.compile(r"^{}:\\.*>".format(os.getcwd()[0]), re.M)
- def __init__(self, proc, prompt=default_prompt):
- self.proc = proc
- self.prompt = prompt
- self.output = ""
- self.changed = True
- def kill(self):
- self.send("exit")
- self.proc.kill()
- def get(self):
- if self.changed:
- self.changed = False
- while not self.prompt.search(self.output):
- c = self.proc.stdout.read(1)
- if c == "" or c is None:
- break
- self.output += c
- output, self.output = self.output, ""
- return output
- else:
- return "Process is likely dead. Please reconnect."
- def send(self, cmd):
- try:
- if not isinstance(cmd, str):
- cmd = cmd.decode()
- if self.proc.poll() is None:
- self.changed = True
- self.proc.stdin.write(cmd + "\n")
- return True
- except Exception as e:
- print(e)
- traceback.print_exc()
- return False
- def __call__(self, cmd):
- try:
- if self.send(cmd):
- return self.get()
- except Exception as e:
- print(e)
- traceback.print_exc()
- return ""
- class CustomHandler(asyncore.dispatcher_with_send):
- BUFFER_SIZE = 2048
- def __init__(self, sock, srv, cli):
- asyncore.dispatcher_with_send.__init__(self, sock)
- sock.send(cli.get())
- self.srv = srv
- self.cli = cli
- def handle_read(self):
- data = self.recv(self.BUFFER_SIZE)
- if data is not None:
- try:
- self.send(self.cli(data))
- except Exception as e:
- print(e)
- traceback.print_exc()
- def handle_close(self):
- if self.srv.remove_client(self) is True:
- print("Client disconnected...")
- self.cli.kill()
- self.close()
- class CustomServer(asyncore.dispatcher):
- def __init__(self, addr, port):
- asyncore.dispatcher.__init__(self)
- self.conns = {}
- self.create_socket(AF_INET, SOCK_STREAM)
- self.set_reuse_addr()
- self.bind((addr, port))
- self.listen(5)
- def remove_client(self, client):
- removed = False
- try:
- del self.conns[client.fileno()]
- removed = True
- except KeyError:
- removed = False
- finally:
- return removed
- def handle_accept(self):
- con = self.accept()
- if con is not None:
- sock, (addr, port,) = con
- print("New client connected from {}:{}".format(addr, port))
- # if sock.fileno() not in self.conns:
- self.conns[sock.fileno()] = CustomHandler(sock, self, WinCLI(subprocess.Popen(["cmd.exe"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)))
- print(self.conns)
- def main(host, port):
- CustomServer(host, port)
- print("Listening on {}:{}...".format(host, port))
- asyncore.loop()
- if __name__ == '__main__':
- main("0.0.0.0", 1234)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement