Skip to content

Instantly share code, notes, and snippets.

@kamilion
Created November 1, 2018 04:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamilion/e04c683227554fc2d0bd832314a22e34 to your computer and use it in GitHub Desktop.
Save kamilion/e04c683227554fc2d0bd832314a22e34 to your computer and use it in GitHub Desktop.
A failure of a telnet client.
# telnet program example
import socket, select, sys, _thread
class uTelnet:
# Automatically initialized class variables
# Status variables
connected = False
last_response = ""
# Class methods
def __init__(self, server="rainmaker.wunderground.com", port=23):
self.server = server
self.port = port
def connect(self):
self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.conn.connect((self.server, self.port))
self.connected = True
def send_quit(self, message="Goodbye..."):
self.send_cmd("QUIT", message)
def get_response(self):
return self.conn.recv(1024).decode("utf-8")
def send_cmd(self, cmd, message):
command = "{} {}\r\n".format(cmd, message).encode("utf-8")
self.conn.send(command)
def send_msg(self, message):
command = "{}".format(message).encode("utf-8")
self.conn.send(command)
# End of uTelnet class
# _thread target function to print responses
def print_response():
while(client.connected):
client.last_response = client.get_response()
if(client.last_response != ''):
if "Closing Link" in client.last_response: # Server said goodbye
client.connected = False # So we're disconnected now, thread ends.
print("{}".format(client.last_response.strip())) # Print the response.
# socket conn.receive blocks the program until a response is received
# to prevent blocking program execution, receive should be threaded
def go():
cmd = "" # Start with an empty string
client.connect() # Connect to the server
_thread.stack_size(10*1024) # Get a 10KB Stack
enginethread = _thread.start_new_thread("uTelnet", print_response, ())
_thread.stack_size(4*1024) # Go back to 4KB
# Loop until quit, _thread will handle printing.
while(cmd != "/quit"):
cmd = input(" ")
if cmd == "/quit":
client.send_quit()
client.send_msg(cmd)
# End of functions
client = uTelnet() # Create the client object so it is a global to the REPL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment