from twisted.internet.protocol import ServerFactory, Protocol
from twisted.conch.telnet import StatefulTelnetProtocol
from twisted.internet import reactor
import new_subprocess
from time import sleep

class ShellTelnet():
    def __init__(self):
        self.shell = 'cmd /u /q'
        self.tail = '\r\n'
        self.MyShell = new_subprocess.Popen(self.shell, stdin=new_subprocess.PIPE, stdout=new_subprocess.PIPE, stderr=new_subprocess.subprocess.STDOUT)
        print "PID ShellTelnet: %d" % self.MyShell.pid

    def getshellpid(self):
        return self.MyShell.pid

    def sendcommand(self, my_cmd):
        print "DEBUB: sendcomand called with *%s*" % repr(my_cmd)
        new_subprocess.send_all(self.MyShell, my_cmd + self.tail)

    def read(self):
        data = 'cls'
        dataread = ''
        while data.strip():
            data = new_subprocess.recv_some(self.MyShell, t=0.1)
            dataread += data
            sleep(0.25)
        print dataread
        return dataread

    def killshell(self):
        import ctypes
        ctypes.windll.kernel32.TerminateProcess(int(self.MyShell._handle), -1)

class MyProtocol(StatefulTelnetProtocol):
    def connectionMade(self):
        print "DEBUG: connectionMade called"
        self.sendLine("***************************************\r\n")
        self.sendLine("Welcome to the Simplified Telnet Server\r\n")
        self.sendLine("***************************************\r\n")
        self.Shell = ShellTelnet()
        self.sendLine("The telnet shell PID on the server is %d" % self.Shell.getshellpid())
        sleep(2)
        self.transport.write(self.Shell.read().strip())
        self.clearLineBuffer()

    def lineReceived(self, line):
        print "DEBUG: lineReceived called with %s" % line
        if line.strip() != "exit":
            self.Shell.sendcommand(line.strip())
            self.transport.write(self.Shell.read().strip())
        else:
            self.Shell.killshell()
            self.sendLine("TelnetShell killed. Bye Bye ...")
            self.transport.loseConnection()
        self.clearLineBuffer()
        
    def connectionLost(self, reason):
        print "DEBUG: connectionLost called with: %s" % str(reason)

def CreateMyFactory():
    factory = ServerFactory()
    factory.protocol = MyProtocol
    return factory

if __name__ == "__main__":
    MaFactory = CreateMyFactory()
    reactor.listenTCP(8023, MaFactory)
    reactor.run()

