vcast_license_usage_server/server.py

109 lines
3.4 KiB
Python
Raw Normal View History

2025-01-05 09:59:40 +08:00
#!/usr/bin/python3
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import os
from pathlib import Path
sample_data = {
"27003@szmis03": {
"name": "27003@szmis03",
"total": 2,
"used": 2,
"used_info": [
{
"user": "ekko.bao",
"host": "szl3bc1808",
"login_time": "58.9h"
},
{
"user": "zzc",
"host": "szl3bc1808",
"login_time": "58.9h"
}
]
},
"27003@szmis05": {
"name": "27003@szmis05",
"total": 2,
"used": 0,
"used_info": []
},
"27003@szmis10": {
"name": "27003@szmis10",
"total": 2,
"used": 1,
"used_info": [{
"user": "zzc33333",
"host": "szl3bc1808",
"login_time": "58.9h"
}]
}
}
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return # 重写该方法以禁用日志输出
def do_GET(self):
if self.path == '/vcast/lic_use_info':
self.send_response(200)
self.send_header('Content-type', 'text/json')
self.end_headers()
data = json.dumps(sample_data)
self.wfile.write(data.encode('utf-8'))
return
path = self.path
if path == '/':
path = '/index.html'
path = path.strip('/')
if not self.send_file(path):
self.send_404()
def send_404(self):
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"<h1>404 Not Found</h1><p>The page you are looking for does not exist.</p>")
def send_file(self, file_path) -> bool:
file_path =str(Path(os.path.abspath(__file__)).parent.joinpath(file_path))
print(f"clinet request: [{file_path}]")
if not os.path.isfile(file_path):
return False
self.send_response(200)
mime_type = self.get_mime_type(file_path)
self.send_header('Content-type', mime_type)
if mime_type.startswith('text/'):
self.send_header('Content-Disposition', f'inline; filename={os.path.basename(file_path)}')
else:
self.send_header('Content-Disposition', f'attachment; filename={os.path.basename(file_path)}')
self.end_headers()
with open(file_path, 'rb') as f:
self.wfile.write(f.read())
return True
def get_mime_type(self, file_path):
ext = os.path.splitext(file_path)[1]
if ext == '.txt':
return 'text/plain'
elif ext == '.js':
return 'application/javascript'
elif ext == '.html':
return 'text/html'
elif ext == '.css':
return 'text/css'
# 添加更多 MIME 类型根据需要
return 'application/octet-stream' # 默认类型
def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port=8088):
server_address = ('0.0.0.0', port)
httpd = server_class(server_address, handler_class)
print(f'Starting server on {server_address[0]}:{server_address[1]} ...')
httpd.serve_forever()
if __name__ == "__main__":
if len(os.sys.argv) > 1:
run(port=int(os.sys.argv[1]))
else:
run()