Advertisement
MegaLoler

Telnet Server Library

Jul 31st, 2012
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.16 KB | None | 0 0
  1. import socket
  2. import select
  3.  
  4. # Telnet Server
  5. # By MegaLoler
  6. # Version 0.1
  7.  
  8. # The TelnetClientConnection class
  9. # This class handles the client connections
  10. # Subclass this to define your own event handlers and then pass your subclass as the ConnectionClass argument in the TelnetServer class
  11.  
  12. class TelnetClientConnection:
  13.     def __init__(self, sock, addr):
  14.         self.sock = sock
  15.         self.addr = addr
  16.        
  17.         self.buf = ""
  18.        
  19.         self.connected = True
  20.         self.onConnect()
  21.        
  22.     def recv(self, data):
  23.         try:
  24.             data = data.decode()
  25.             self.buf += data
  26.            
  27.             for char in data:
  28.                 self.onCharInput(char)
  29.            
  30.             if "\r\n" in self.buf:
  31.                 lines = self.buf.split("\r\n")
  32.             elif "\r\x00" in self.buf:
  33.                 lines = self.buf.split("\r\x00")
  34.             else:
  35.                 lines = None
  36.            
  37.             if lines:
  38.                 self.buf = lines.pop()
  39.                 for line in lines:
  40.                     self.onLineInput(line.strip())
  41.         except UnicodeDecodeError as exception:
  42.             pass
  43.    
  44.     # Commands
  45.    
  46.     # Disconnects the client
  47.     def disconnect(self):
  48.         self.sock.close()
  49.        
  50.         self.connected = False
  51.         self.onDisconnect()
  52.    
  53.     # Sends exact data
  54.     def send(self, data):
  55.         if self.connected: self.sock.send(data.encode())
  56.    
  57.     # Sends a line of data
  58.     def sendLine(self, line):
  59.         self.send(line.strip() + "\r\n")
  60.    
  61.     # Events
  62.    
  63.     # Triggered when the connection is established
  64.     def onConnect(self):
  65.         print("[TELNET] " + str(self.addr) + " has connected.")
  66.         self.sendLine("Welcome to this telnet server thingy!")
  67.    
  68.     # Triggered when the connection is broken
  69.     def onDisconnect(self):
  70.         print("[TELNET] " + str(self.addr) + " has disconnected.")
  71.        
  72.     # Triggered when a single character is sent from the client (only works if the telnet client is in char mode)
  73.     def onCharInput(self, char):
  74.         pass
  75.    
  76.     # Triggered when the client presses enter
  77.     def onLineInput(self, line):
  78.         print("[TELNET] " + str(self.addr) + ": " + line)
  79.         self.sendLine("I'd like to inform you that you typed \"" + line + "\"")
  80.  
  81. # The TelnetServer class
  82. # Use the ConnectionClass parameter when you define your own subclasses of TelnetClientConnection to handle the events
  83.  
  84. class TelnetServer:
  85.     def __init__(self, host = socket.gethostname(), port = 23, maxQueue = 5, ConnectionClass = TelnetClientConnection):
  86.         self.sock = socket.socket()
  87.         self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  88.         self.sock.bind((host, port))
  89.         self.sock.listen(maxQueue)
  90.        
  91.         self.ConnectionClass = ConnectionClass
  92.         self.clients = {}
  93.        
  94.         self.running = False
  95.    
  96.     # Start the server
  97.     def start(self):
  98.         if not self.running:
  99.             self.running = True
  100.            
  101.             while self.running:
  102.                 (rlist, wlist, xlist) = select.select(list(self.clients.keys()) + [self.sock], [], [])
  103.                 for s in rlist:
  104.                     if s == self.sock:
  105.                         (client, address) = self.sock.accept()
  106.                         self.clients[client] = self.ConnectionClass(client, address)
  107.                     else:
  108.                         data = s.recv(1024)
  109.                         if len(data) == 0:
  110.                             self.clients[client].disconnect()
  111.                             del self.clients[client]
  112.                         else:
  113.                             self.clients[client].recv(data)
  114.    
  115.     # Stop the server
  116.     def stop(self):
  117.         if self.running:
  118.             self.running = False
  119.  
  120. if __name__ == "__main__":
  121.     TelnetServer(port = 1234).start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement