-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpOpenFile-0.py
More file actions
86 lines (71 loc) · 3.27 KB
/
HttpOpenFile-0.py
File metadata and controls
86 lines (71 loc) · 3.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
import shutil
import platform
import http.server
import socketserver
import subprocess
from urllib.parse import urlparse, unquote_plus
class SimpleHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
# 解析 URL
parsed = urlparse(self.path)
query = unquote_plus(parsed.query)
# 检查路径是否为 '/open'
if parsed.path != '/open':
self.send_error(401, "Unauthorized")
return
# 设置 http 响应状态码
self.send_response(200)
# 设置 http 响应头
self.send_header('Content-type', 'text/html;charset=utf-8')
self.end_headers()
# 设置 html 样式
self.wfile.write(r"<style>body{padding:20vh}</style>".encode())
self.wfile.write(r"<style>div,green,red,small{display:block;text-align:center}</style>".encode())
self.wfile.write(r"<style>div{margin-bottom:20px}</style>".encode())
self.wfile.write(r"<style>green{color:green;font-weight:bold}</style>".encode())
self.wfile.write(r"<style>red{color:red;font-weight:bold}</style>".encode())
# 检查请求
if self.client_address[0] != "127.0.0.1" and self.client_address[0] != "localhost":
self.wfile.write("<red>非本机请求,拒绝访问 *_*</red>".encode())
return
# 获取系统信息
system = platform.system()
# 如果不是绝对路径,则设置根目录为用户主目录
if not os.path.isabs(query):
query = os.path.join(os.environ["USERPROFILE"] if system == "Windows" else os.environ["HOME"], query)
self.wfile.write("<div>{}</div>".format(query).encode())
# 检查目录或文件是否存在
if os.path.isdir(query):
print(">>>> is dir >>>> " + query)
elif os.path.isfile(query):
print(">>>> is file >>>> " + query)
else:
self.wfile.write("<red>目录或文件不存在 *_*</red>".encode())
return
try:
# 打开文件,分系统执行
if system == "Windows":
os.startfile(query)
elif system == "Darwin":
subprocess.call(['open', query])
elif system == "Linux":
if shutil.which("xdg-open") is not None:
subprocess.call(['xdg-open', query])
else:
self.wfile.write(("<red>请先<a href='https://www.bing.com/search?q=xdg-utils%20%E5%AE%89%E8%A3%85'>" +
"安装 xdg-utils</a>,然后重试 *_*</red>").encode())
return
else:
self.wfile.write("<red>不支持的操作系统:{} *_*</red>".format(system).encode())
return
except Exception as e:
self.wfile.write("<red>打开失败 *_*</red><br/>".encode())
self.wfile.write("<small>{}</small>".format(e).encode())
return
self.wfile.write("<green>已经在相关应用中打开,请关闭本窗口 ^_^</green>".encode())
self.wfile.write("<script>window.close()</script>".encode())
PORT = 8000
with socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()