Need help with a simple server

Graeme Matthew gsmatthew at ozemail.com.au
Mon Jun 2 07:56:12 EDT 2003


Sam not sure if this helps, ive just written this for a threaded server that
im going to use in an app, excuse the code but it needs exception handling
and cleaning up
hope it hepls, ive put comments in to help you

cheers

graeme

import SocketServer
import socket
import sys
from time import time, ctime
import os

PORT = 55555            #DEFAULT VALUE FOR PORT TO LISTENING ON
HOST = 'localhost'      #HOST DEFAULTS TO localhost
VERSION = 'v0.1'        #Version for this server script



#Here create your own server class and inherit from BaseRequestHandler
class AppServerHandler(SocketServer.BaseRequestHandler):
    """ Class for handling incoming socket requests"""

    #you must name this function handle as your overiding the inherited
handler
    def handle(self):
        """ handle overide """

        sys.stdout.flush()
        print 'CONNECTED\t[%s]\t[%s]' % (str(self.client_address),
ctime(time()))
        msg = self.request.recv(1024)
        print msg
        #print '\tRECV\t[%d]\tBYTES' % len(msg)
        #print 'Request Size [%d] bytes' % len(msg)
        self.request.send('Processed [%d] bytes' % len(msg))
        #print "\tSENT\t[%d]\tBYTES" % len(msg)


#just a little wrapper function to start server
def StartServer():

    print '[Application Server\t[RUNNING], listening for connections'
    server = SocketServer.ThreadingTCPServer
    listenAddress = (HOST, PORT)
    #notice how u put your own class inside here it will be called on each
request
    server(listenAddress, AppServerHandler).serve_forever()

StartServer()


"Sam Pro" <spro1 at uic.edu> wrote in message
news:fb97d86e.0306011538.2f8a7a0a at posting.google.com...
> I am trying to write my first simple server and would like some ideas
> on improving its stability and security.  I want to write something
> that is as reliable and secure as possible and need to know what I
> need to look out for.  After the code is complete I plan on writing a
> client and piping it through something like Stunnel (SSL).  It would
> then be used for the exchange of classified data.  My biggest consern
> at this point is that if I run nmap through the port that the server
> is running I get:
>
> Traceback (most recent call last):
>   File "server.py", line 28, in ?
>      input = conn.recv(1024)
> socket.error: (104, 'Connection reset by peer')
>
> I can't have the server crashing at something so trivial.  It seems
> that the buffer isn't big enough to handle nmaps probe???  What should
> I do?  What other input could cause a crash like that?  As of now  I
> am just learning Python so please forgive and point out any idiotic
> mistakes or retarded code.
>
> To login to my server telnet to it (port 55000) and issue "USER sam"
> and then "sam" when prompted for the password.  After that you can
> issue "HELP" to get a list of commands.
>
> Thanks,
>
> Sam
>
> ----------START CODE-----------
>
> from socket import *
> HOST = 'localhost'        # Symbolic name meaning the local host
> PORT = 55000              # Arbitrary non-privileged server
> WELCOMEMESSAGE = 'Greetings from SamServer V0.1\n'
> HELPMESSAGE = '''HELO - Display welcome message
> HELP - Display this command listing
> ECHO - Echo string (eg ECHO Hello world)
> QUIT - Exit session
> KILL - Terminate server
> '''
> serverUp = 1
> prompt = '->'
> s = socket(AF_INET, SOCK_STREAM)
> s.bind((HOST, PORT))
> s.listen(1)
> while serverUp == 1:
>   userAuth = 0
>   print 'Waiting for connection...'
>   conn, addr = s.accept()
>   print '+++Connected by', addr, '+++'
>   while 1:                       # Login access
>       cmdstr = '<NULL>'
>       command = 'NULL'
>       conn.send(prompt)
>       input = conn.recv(1024)
>       command = input[0:4]
>       if len(input[4:]) > 2: cmdstr = input[5:len(input[4:0])-2]
>       if command == 'USER':
>         if cmdstr == 'sam':
>           conn.send('PASS: ')
>           input = conn.recv(1024)
>   if input[:-2] == 'sam':
>             userAuth = 1
>             print 'Login success by:', cmdstr
>     break
>           else:
>     print '***User', cmdstr, 'provided wrong password!', ' Tried:',
> input[:-2]
>     break
> else:
>   print '***User:', cmdstr, 'not found!'
>           break
>       else:
>         print '***ISSUED COMMAND OTHER THEN \"USER\"!'
> break
>
>   while userAuth == 1:                       # Command loop
>       cmdstr = '<NULL>'
>       command = 'NULL'
>       conn.send(prompt)
>       input = conn.recv(1024)
>       command = input[0:4]
>       if len(input[4:]) > 2: cmdstr = input[5:len(input[4:0])-2]
>       if command == 'HELO': conn.send(WELCOMEMESSAGE)
>       if command == 'HELP': conn.send(HELPMESSAGE)
>       if command == 'QUIT': break
>       if command == 'ECHO':
>            conn.send(cmdstr)
>            conn.send('\n')
>       if command == 'KILL':
>            serverUp = 0
>            break
>
>       print command, ' issued @ ', 'TIME', ' with ', cmdstr
>   conn.close()
>   print '---Connection closed to', addr, '---'






More information about the Python-list mailing list