1. 程式人生 > >簡單http和https伺服器python指令碼

簡單http和https伺服器python指令碼

歡迎加入python學習交流群 667279387

工作經常要用到測試http和https協議,這裡寫了兩個簡單的指令碼實現簡單的http伺服器和https伺服器。

http伺服器程式碼

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()

https伺服器程式碼

# 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()

歡迎加入python學習交流群 667279387