Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 30th, 2012  |  syntax: None  |  size: 2.16 KB  |  hits: 20  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import socket
  2. import sys,time,datetime,string, os
  3.  
  4.  
  5. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  6. #localhost port 5555
  7. s.bind(('',5555))
  8. s.listen(1)
  9.  
  10. #http header actions
  11. firstheader ='HTTP/1.0 200 OK\r\nServer: Custom\r\nDate:   \r\nContent-Type: text/html\r\n\r\n'
  12.  
  13.  
  14. #NOTE: all print statements show up only on server *console*
  15.  
  16. #determine if file exists or not
  17. def requestfile(fname):
  18.  
  19.   if os.path.isfile(fn) == False:
  20.       return False
  21.   else:
  22.       return True
  23.  
  24.  
  25. while True:
  26.  
  27.       conn, addr = s.accept()
  28.  
  29.       data = conn.recv(1024)
  30.  
  31.       print data
  32.       #split up parts of the contents in list/array
  33.       r = data.split()
  34.       f = r[1]
  35.       #split / from url
  36.       fn = f[1:len(f)]
  37.  
  38.       #normal http GET resquests
  39.       if r[0] == 'GET':
  40.       #get file from GET header
  41.  
  42.          print requestfile(f)
  43.  
  44.          #if no defaultfile dish out index file
  45.          if f == '/':
  46.              u = open('index.html','r').read()
  47.              conn.send(firstheader+str(u))
  48.          else:
  49.            #if file exists, dish out error file
  50.            if requestfile(f) == False:
  51.                #trigger error file
  52.                u = open('error.html','r').read()
  53.                conn.send(firstheader+str(u))
  54.            #if file does exist, open the file and pipe it to user
  55.            if requestfile(f) == True:
  56.  
  57.               u = open(fn,'r').read()
  58.               conn.send(firstheader+str(u))
  59.  
  60.            #shuts server down
  61.            if f == '/shutdown.html':
  62.            
  63.               print "server has been shutdown"
  64.               sys.exit()
  65.               break
  66.  
  67.       #handle post requests, when someone submits a form
  68.       if r[0] == 'POST':
  69.  
  70.          print "POST MADE"
  71.  
  72.  
  73.          a = r.index("Content-Length:")+2
  74.          qs = r[a]
  75.  
  76.          #put POST query into a dictionary
  77.          d = dict([x.split("=") for x in qs.split("&")])
  78.  
  79.          #print out the variables from post
  80.          print "USERNAME: "+ d['user']
  81.          print "PASSWORD: "+ d['pass']
  82.  
  83.          u = open(fn,'r').read()
  84.          conn.send(firstheader+str(u))
  85.  
  86.  
  87.       conn.close()
  88.       print "connect closed...still listening"