简单http和https服务器pytho

2023-01-31 05:01:57 https 服务器 简单

欢迎加入python学习交流群 667279387

工作经常要用到测试Httphttps协议,这里写了两个简单的脚本实现简单的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

相关文章