File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ title : python自建简单的文件服务器
3
+ date : 2024-08-13 17:54:36
4
+ tags :
5
+ ---
6
+
7
+ ### 为啥有这个?
8
+
9
+ 内网主机之间无法通过scp拷贝文件。通过如下脚本启动pytho程序接收文件。
10
+
11
+ nc也可以,但是nc对于单文件来说比较好,多文件了就不行了。
12
+
13
+ ### 服务器代码
14
+
15
+ ``` python
16
+ import os
17
+ from http.server import SimpleHTTPRequestHandler, HTTPServer
18
+
19
+ class CustomHTTPRequestHandler (SimpleHTTPRequestHandler ):
20
+ def do_PUT (self ):
21
+ length = int (self .headers[' Content-Length' ])
22
+ path = self .translate_path(self .path)
23
+ directory = os.path.dirname(path)
24
+
25
+ # 创建目录结构
26
+ if not os.path.exists(directory):
27
+ os.makedirs(directory)
28
+
29
+ with open (path, ' wb' ) as f:
30
+ f.write(self .rfile.read(length))
31
+ self .send_response(201 , " Created" )
32
+ self .end_headers()
33
+
34
+ if __name__ == ' __main__' :
35
+ server_address = (' ' , 8000 )
36
+ httpd = HTTPServer(server_address, CustomHTTPRequestHandler)
37
+ print (" Serving on port 8000..." )
38
+ httpd.serve_forever()
39
+ ```
40
+
41
+ ### 使用
42
+
43
+ #### 上传
44
+
45
+ ``` shell
46
+ curl -X PUT --upload-file ' xxx.log' http://xxx.96.xxx.60:8000/2024-08/
47
+ ```
48
+
49
+ #### 下载
50
+
51
+ - 页面点击直接下载
52
+ - shell: wget http://localhost:8000/example.txt
You can’t perform that action at this time.
0 commit comments