Advertisement
metalx1000

Very Basic Python Telnet Server using Socket

Jun 24th, 2018
887
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import socket
  3. import sys
  4. from thread import *
  5. import commands
  6.  
  7. HOST = ''   # Symbolic name meaning all available interfaces
  8. PORT = 8888 # Arbitrary non-privileged port
  9.  
  10. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  11. print 'Socket created'
  12.  
  13. #Bind socket to local host and port
  14. try:
  15.     s.bind((HOST, PORT))
  16. except socket.error as msg:
  17.     print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
  18.     sys.exit()
  19.      
  20. print 'Socket bind complete'
  21.  
  22. #Start listening on socket
  23. s.listen(10)
  24. print 'Socket now listening'
  25.  
  26. #Function for handling connections. This will be used to create threads
  27. def clientthread(conn):
  28.     #Sending message to connected client
  29.     conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
  30.      
  31.     #infinite loop so that function do not terminate and thread do not end.
  32.     while True:
  33.          
  34.         #Receiving from client
  35.         data = conn.recv(1024).rstrip()
  36.         reply = 'OK...' + data
  37.         if not data:
  38.             break
  39.      
  40.         print data
  41.         status, output = commands.getstatusoutput(data)
  42.         conn.sendall(output)
  43.         conn.send("\n>>> ")
  44.      
  45.     #came out of loop
  46.     conn.close()
  47.  
  48. #now keep talking with the client
  49. while 1:
  50.     #wait to accept a connection - blocking call
  51.     conn, addr = s.accept()
  52.     print 'Connected with ' + addr[0] + ':' + str(addr[1])
  53.      
  54.     #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
  55.     start_new_thread(clientthread ,(conn,))
  56.  
  57. s.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement