Repository navigation
Expand file tree
/
Copy pathnas_server.py
More file actions
177 lines (154 loc) · 6.93 KB
/
Copy pathnas_server.py
File metadata and controls
177 lines (154 loc) · 6.93 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import os
import json
import requests
from bs4 import BeautifulSoup
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from urllib.parse import unquote, parse_qs, urlparse
from email.parser import BytesParser
from io import BytesIO
import socket
import mimetypes
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass
class NASHandler(BaseHTTPRequestHandler):
def _set_headers(self, content_type='text/html', status=200):
self.send_response(status)
self.send_header('Content-type', content_type)
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
def _send_file(self, path, default_type='text/html'):
try:
with open(path, 'rb') as f:
content_type = mimetypes.guess_type(path)[0] or default_type
self._set_headers(content_type)
self.wfile.write(f.read())
except FileNotFoundError:
self._set_headers(status=404)
self.wfile.write(b'404 Not Found')
except Exception as e:
self._set_headers(status=500)
self.wfile.write(f'500 Server Error: {str(e)}'.encode())
def _get_baidu_hot(self):
"""获取百度热搜50条"""
try:
url = "https://top.baidu.com/board?tab=realtime"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers, timeout=5)
soup = BeautifulSoup(response.text, 'html.parser')
items = [item.text.strip() for item in soup.select('div.c-single-text-ellipsis')[:50]]
return {'status': 'success', 'data': items}
except Exception as e:
return {'status': 'error', 'message': str(e)}
def _crawl_url(self, url):
"""抓取自定义URL内容"""
try:
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers, timeout=5)
soup = BeautifulSoup(response.text, 'html.parser')
# 清理内容
for tag in soup(['script', 'style', 'iframe', 'nav', 'footer']):
tag.decompose()
title = soup.title.string if soup.title else '无标题'
content = '\n'.join(p.get_text().strip() for p in soup.find_all(['p', 'h1', 'h2', 'h3']))
return {
'status': 'success',
'title': title,
'content': content[:5000] + '...' if len(content) > 5000 else content,
'url': url
}
except Exception as e:
return {'status': 'error', 'message': str(e)}
def do_GET(self):
path = self.path.split('?')[0].split('#')[0]
query = parse_qs(urlparse(self.path).query)
if path == '/':
self._send_file('index.html')
elif path == '/index.html':
self._send_file('index.html')
elif path == '/resou.html':
if 'url' in query:
# 自定义URL抓取
result = self._crawl_url(query['url'][0])
elif 'action' in query and query['action'][0] == 'baidu_hot':
# 百度热搜
result = self._get_baidu_hot()
else:
# 返回原始resou.html页面
self._send_file('resou.html')
return
self._set_headers('application/json')
self.wfile.write(json.dumps(result).encode())
elif path == '/api/list':
self._handle_file_list()
elif os.path.exists('.' + path):
self._send_file('.' + path)
else:
self._set_headers(status=404)
self.wfile.write(b'404 Not Found')
def _handle_file_list(self):
try:
files = []
for item in os.listdir('.'):
if item not in ['nas_server.py'] and not item.startswith('.'):
full_path = os.path.join('.', item)
files.append({
'name': item,
'path': '/' + item,
'size': os.path.getsize(full_path),
'type': 'dir' if os.path.isdir(full_path) else 'file'
})
self._set_headers('application/json')
self.wfile.write(json.dumps(files).encode())
except Exception as e:
self._set_headers('application/json', 500)
self.wfile.write(json.dumps({'error': str(e)}).encode())
def do_POST(self):
if self.path == '/upload':
try:
content_type = self.headers.get('Content-Type', '')
if not content_type.startswith('multipart/form-data'):
raise ValueError("Invalid content type")
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length)
parser = BytesParser()
message = parser.parsebytes(b'Content-Type: ' + content_type.encode() + b'\r\n\r\n' + body)
for part in message.walk():
if part.get_filename():
filename = unquote(part.get_filename())
safe_name = "".join(c for c in filename if c.isalnum() or c in (' ', '.', '_', '-')).rstrip()
with open(safe_name, 'wb') as f:
f.write(part.get_payload(decode=True))
self._set_headers('application/json')
self.wfile.write(json.dumps({
'status': 'success',
'filename': safe_name
}).encode())
return
self._set_headers('application/json', 400)
self.wfile.write(json.dumps({'error': 'No file uploaded'}).encode())
except Exception as e:
self._set_headers('application/json', 500)
self.wfile.write(json.dumps({'error': str(e)}).encode())
else:
self._set_headers(status=404)
self.wfile.write(b'404 Not Found')
def run_server():
PORT = 8000
HOST = '0.0.0.0'
mimetypes.add_type('text/html', '.html')
mimetypes.add_type('image/jpeg', '.jpg')
mimetypes.add_type('image/png', '.png')
server = ThreadingHTTPServer((HOST, PORT), NASHandler)
print(f"\n服务器已启动")
print(f"文件管理: http://{HOST}:{PORT}/index.html")
print(f"爬虫功能: http://{HOST}:{PORT}/resou.html")
print(f"百度热搜: http://{HOST}:{PORT}/resou.html?action=baidu_hot")
print(f"自定义抓取: http://{HOST}:{PORT}/resou.html?url=目标网址")
print("\n按 Ctrl+C 停止")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n服务器已关闭")
if __name__ == '__main__':
run_server()