工作经常要用到测试http和https协议,这里写了两个简单的脚本实现简单的http服务器和https服务器。
import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('127.0.0.1', port)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
# taken from https://gist.github.com/dergachev/7028596
#
# generate server.xml with the following command:
# openssl req -new -x509 -keyout https_svr_key.pem -out https_svr_key.pem -days 3650 -nodes
#
import BaseHTTPServer
import SimpleHTTPServer
import os
import socket
import ssl
script_home = os.path.dirname(os.path.abspath(__file__))
ip = [(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close())
for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
port = 8888
def main():
print ("simple https server, address:%s:%d, document root:%s" % (ip, port, script_home))
httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', port), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./https_svr_key.pem', server_side=True)
httpd.serve_forever()
if __name__ == '__main__':
os.chdir(script_home)
main()