Python搭建简单HTTP上传服务器

在Python中内置了HTTPServer模块,在终端输入如下命令:

  1. $ python3 -m http.server [8000]

就可以在目录下快速建立一个HTTP服务器,只需要在浏览器中输入http://127.0.0.1:8000就可以访问并下载文件了,不过python内置的模块并没有提供上传功能,上传功能需要自己实现,以下是实现上传功能的Python脚本:

  1. #!/usr/bin/env python3
  2. """Simple HTTP Server With Upload.
  3. This module builds on BaseHTTPServer by implementing the standard GET
  4. and HEAD requests in a fairly straightforward manner.
  5. see: https://gist.github.com/UniIsland/3346170
  6. """
  7. __version__ = "0.1"
  8. __all__ = ["SimpleHTTPRequestHandler"]
  9. __author__ = "bones7456"
  10. __home_page__ = "http://li2z.cn/"
  11. import os
  12. import posixpath
  13. import http.server
  14. import urllib.request, urllib.parse, urllib.error
  15. import cgi
  16. import shutil
  17. import mimetypes
  18. import re
  19. from io import BytesIO
  20. class SimpleHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
  21. """Simple HTTP request handler with GET/HEAD/POST commands.
  22. This serves files from the current directory and any of its
  23. subdirectories. The MIME type for files is determined by
  24. calling the .guess_type() method. And can reveive file uploaded
  25. by client.
  26. The GET/HEAD/POST requests are identical except that the HEAD
  27. request omits the actual contents of the file.
  28. """
  29. server_version = "SimpleHTTPWithUpload/" + __version__
  30. def do_GET(self):
  31. """Serve a GET request."""
  32. f = self.send_head()
  33. if f:
  34. self.copyfile(f, self.wfile)
  35. f.close()
  36. def do_HEAD(self):
  37. """Serve a HEAD request."""
  38. f = self.send_head()
  39. if f:
  40. f.close()
  41. def do_POST(self):
  42. """Serve a POST request."""
  43. r, info = self.deal_post_data()
  44. print((r, info, "by: ", self.client_address))
  45. f = BytesIO()
  46. f.write(b'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
  47. f.write(b"<html>\n<title>Upload Result Page</title>\n")
  48. f.write(b"<body>\n<h2>Upload Result Page</h2>\n")
  49. f.write(b"<hr>\n")
  50. if r:
  51. f.write(b"<strong>Success:</strong>")
  52. else:
  53. f.write(b"<strong>Failed:</strong>")
  54. f.write(info.encode())
  55. f.write(("<br><a href=\"%s\">back</a>" % self.headers['referer']).encode())
  56. f.write(b"<hr><small>Powerd By: bones7456, check new version at ")
  57. f.write(b"<a href=\"http://li2z.cn/?s=SimpleHTTPServerWithUpload\">")
  58. f.write(b"here</a>.</small></body>\n</html>\n")
  59. length = f.tell()
  60. f.seek(0)
  61. self.send_response(200)
  62. self.send_header("Content-type", "text/html")
  63. self.send_header("Content-Length", str(length))
  64. self.end_headers()
  65. if f:
  66. self.copyfile(f, self.wfile)
  67. f.close()
  68. def deal_post_data(self):
  69. print(self.headers)
  70. content_type = self.headers['content-type']
  71. if not content_type:
  72. return (False, "Content-Type header doesn't contain boundary")
  73. boundary = content_type.split("=")[1].encode()
  74. remainbytes = int(self.headers['content-length'])
  75. line = self.rfile.readline()
  76. remainbytes -= len(line)
  77. if not boundary in line:
  78. return (False, "Content NOT begin with boundary")
  79. line = self.rfile.readline()
  80. remainbytes -= len(line)
  81. fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line.decode())
  82. if not fn:
  83. return (False, "Can't find out file name...")
  84. path = self.translate_path(self.path)
  85. fn = os.path.join(path, fn[0])
  86. line = self.rfile.readline()
  87. remainbytes -= len(line)
  88. line = self.rfile.readline()
  89. remainbytes -= len(line)
  90. try:
  91. out = open(fn, 'wb')
  92. except IOError:
  93. return (False, "Can't create file to write, do you have permission to write?")
  94. preline = self.rfile.readline()
  95. remainbytes -= len(preline)
  96. while remainbytes > 0:
  97. line = self.rfile.readline()
  98. remainbytes -= len(line)
  99. if boundary in line:
  100. preline = preline[0:-1]
  101. if preline.endswith(b'\r'):
  102. preline = preline[0:-1]
  103. out.write(preline)
  104. out.close()
  105. return (True, "File '%s' upload success!" % fn)
  106. else:
  107. out.write(preline)
  108. preline = line
  109. return (False, "Unexpect Ends of data.")
  110. def send_head(self):
  111. """Common code for GET and HEAD commands.
  112. This sends the response code and MIME headers.
  113. Return value is either a file object (which has to be copied
  114. to the outputfile by the caller unless the command was HEAD,
  115. and must be closed by the caller under all circumstances), or
  116. None, in which case the caller has nothing further to do.
  117. """
  118. path = self.translate_path(self.path)
  119. f = None
  120. if os.path.isdir(path):
  121. if not self.path.endswith('/'):
  122. # redirect browser - doing basically what apache does
  123. self.send_response(301)
  124. self.send_header("Location", self.path + "/")
  125. self.end_headers()
  126. return None
  127. for index in "index.html", "index.htm":
  128. index = os.path.join(path, index)
  129. if os.path.exists(index):
  130. path = index
  131. break
  132. else:
  133. return self.list_directory(path)
  134. ctype = self.guess_type(path)
  135. try:
  136. # Always read in binary mode. Opening files in text mode may cause
  137. # newline translations, making the actual size of the content
  138. # transmitted *less* than the content-length!
  139. f = open(path, 'rb')
  140. except IOError:
  141. self.send_error(404, "File not found")
  142. return None
  143. self.send_response(200)
  144. self.send_header("Content-type", ctype)
  145. fs = os.fstat(f.fileno())
  146. self.send_header("Content-Length", str(fs[6]))
  147. self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
  148. self.end_headers()
  149. return f
  150. def list_directory(self, path):
  151. """Helper to produce a directory listing (absent index.html).
  152. Return value is either a file object, or None (indicating an
  153. error). In either case, the headers are sent, making the
  154. interface the same as for send_head().
  155. """
  156. try:
  157. list = os.listdir(path)
  158. except os.error:
  159. self.send_error(404, "No permission to list directory")
  160. return None
  161. list.sort(key=lambda a: a.lower())
  162. f = BytesIO()
  163. displaypath = cgi.escape(urllib.parse.unquote(self.path))
  164. f.write(b'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
  165. f.write(("<html>\n<title>Directory listing for %s</title>\n" % displaypath).encode())
  166. f.write(("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath).encode())
  167. f.write(b"<hr>\n")
  168. f.write(b"<form ENCTYPE=\"multipart/form-data\" method=\"post\">")
  169. f.write(b"<input name=\"file\" type=\"file\"/>")
  170. f.write(b"<input type=\"submit\" value=\"upload\"/></form>\n")
  171. f.write(b"<hr>\n<ul>\n")
  172. for name in list:
  173. fullname = os.path.join(path, name)
  174. displayname = linkname = name
  175. # Append / for directories or @ for symbolic links
  176. if os.path.isdir(fullname):
  177. displayname = name + "/"
  178. linkname = name + "/"
  179. if os.path.islink(fullname):
  180. displayname = name + "@"
  181. # Note: a link to a directory displays with @ and links with /
  182. f.write(('<li><a href="%s">%s</a>\n'
  183. % (urllib.parse.quote(linkname), cgi.escape(displayname))).encode())
  184. f.write(b"</ul>\n<hr>\n</body>\n</html>\n")
  185. length = f.tell()
  186. f.seek(0)
  187. self.send_response(200)
  188. self.send_header("Content-type", "text/html")
  189. self.send_header("Content-Length", str(length))
  190. self.end_headers()
  191. return f
  192. def translate_path(self, path):
  193. """Translate a /-separated PATH to the local filename syntax.
  194. Components that mean special things to the local file system
  195. (e.g. drive or directory names) are ignored. (XXX They should
  196. probably be diagnosed.)
  197. """
  198. # abandon query parameters
  199. path = path.split('?',1)[0]
  200. path = path.split('#',1)[0]
  201. path = posixpath.normpath(urllib.parse.unquote(path))
  202. words = path.split('/')
  203. words = [_f for _f in words if _f]
  204. path = os.getcwd()
  205. for word in words:
  206. drive, word = os.path.splitdrive(word)
  207. head, word = os.path.split(word)
  208. if word in (os.curdir, os.pardir): continue
  209. path = os.path.join(path, word)
  210. return path
  211. def copyfile(self, source‵‵‵, outputfile):
  212. """Copy all data between two file objects.
  213. The SOURCE argument is a file object open for reading
  214. (or anything with a read() method) and the DESTINATION
  215. argument is a file object open for writing (or
  216. anything with a write() method).
  217. The only reason for overriding this would be to change
  218. the block size or perhaps to replace newlines by CRLF
  219. -- note however that this the default server uses this
  220. to copy binary data as well.
  221. """
  222. shutil.copyfileobj(source, outputfile)
  223. def guess_type(self, path‵‵‵):
  224. """Guess the type of a file.
  225. Argument is a PATH (a filename).
  226. Return value is a string of the form type/subtype,
  227. usable for a MIME Content-type header.
  228. The default implementation looks the file's extension
  229. up in the table self.extensions_map, using application/octet-stream
  230. as a default; however it would be permissible (if
  231. slow) to look inside the data to make a better guess.
  232. """
  233. base, ext = posixpath.splitext(path)
  234. if ext in self.extensions_map:
  235. return self.extensions_map[ext]
  236. ext = ext.lower()
  237. if ext in self.extensions_map:
  238. return self.extensions_map[ext]
  239. else:
  240. return self.extensions_map['']
  241. if not mimetypes.inited:
  242. mimetypes.init() # try to read system mime.types
  243. extensions_map = mimetypes.types_map.copy()
  244. extensions_map.update({
  245. '': 'application/octet-stream', # Default
  246. '.py': 'text/plain',
  247. '.c': 'text/plain',
  248. '.h': 'text/plain',
  249. })
  250. def test(HandlerClass = SimpleHTTPRequestHandler,
  251. ServerClass = http.server.HTTPServer):
  252. http.server.test(HandlerClass, ServerClass)
  253. if __name__ == '__main__':
  254. test()

将以上文件命名为httpserver.py, 执行命令即可启动服务器:

  1. $ python3 httpserver.py

使用curl命令行上传文件

curl使用-F参数即可实现文件上传

  1. $ curl -F "file=@ambari-server_2.7.3.0-0-dist.deb" -H 'Expect:' http://192.168.2.42:8000
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><html>
  3. <title>Upload Result Page</title>
  4. <body>
  5. <h2>Upload Result Page</h2>
  6. <hr>
  7. <strong>Success:</strong>File '/home/lizhiyong/Programs/emr/emr-agent/emr-agent/src/test/python/emr_agent_test/agent/ambari-server_2.7.3.0-0-dist.deb' upload success!<br><a href="None">back</a><hr><small>Powerd By: bones7456, check new version at <a href="http://li2z.cn/?s=SimpleHTTPServerWithUpload">here</a>.</small></body>
  8. </html>

参考链接