
Untitled
By: a guest on
May 30th, 2012 | syntax:
None | size: 2.16 KB | hits: 20 | expires: Never
import socket
import sys,time,datetime,string, os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#localhost port 5555
s.bind(('',5555))
s.listen(1)
#http header actions
firstheader ='HTTP/1.0 200 OK\r\nServer: Custom\r\nDate: \r\nContent-Type: text/html\r\n\r\n'
#NOTE: all print statements show up only on server *console*
#determine if file exists or not
def requestfile(fname):
if os.path.isfile(fn) == False:
return False
else:
return True
while True:
conn, addr = s.accept()
data = conn.recv(1024)
print data
#split up parts of the contents in list/array
r = data.split()
f = r[1]
#split / from url
fn = f[1:len(f)]
#normal http GET resquests
if r[0] == 'GET':
#get file from GET header
print requestfile(f)
#if no defaultfile dish out index file
if f == '/':
u = open('index.html','r').read()
conn.send(firstheader+str(u))
else:
#if file exists, dish out error file
if requestfile(f) == False:
#trigger error file
u = open('error.html','r').read()
conn.send(firstheader+str(u))
#if file does exist, open the file and pipe it to user
if requestfile(f) == True:
u = open(fn,'r').read()
conn.send(firstheader+str(u))
#shuts server down
if f == '/shutdown.html':
print "server has been shutdown"
sys.exit()
break
#handle post requests, when someone submits a form
if r[0] == 'POST':
print "POST MADE"
a = r.index("Content-Length:")+2
qs = r[a]
#put POST query into a dictionary
d = dict([x.split("=") for x in qs.split("&")])
#print out the variables from post
print "USERNAME: "+ d['user']
print "PASSWORD: "+ d['pass']
u = open(fn,'r').read()
conn.send(firstheader+str(u))
conn.close()
print "connect closed...still listening"