无依赖单文件http-ftp文件服务器(py2)
网上看到的东东,居然在很合适堡垒机上传下载文件的场景。
这个只能在python2版本上跑,
我更改了自定义端口。
下次再改写个py3版本的。
#!/usr/bin/env python """Simple HTTP Server With Upload. This module builds on BaseHTTPServer by implementing the standard GET and HEAD requests in a fairly straightforward manner. ****useage: python hftp.py [port] ****just for python version 2 only! """ __version__ = "0.1" __all__ = ["SimpleHTTPRequestHandler"] __author__ = "bones7456" __home_page__ = "http://luy.li/" import sys import os import posixpath import BaseHTTPServer import urllib import cgi import shutil import mimetypes import re try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Simple HTTP request handler with GET/HEAD/POST commands. This serves files from the current directory and any of its subdirectories. The MIME type for files is determined by calling the .guess_type() method. And can reveive file uploaded by client. The GET/HEAD/POST requests are identical except that the HEAD request omits the actual contents of the file. """ server_version = "SimpleHTTPWithUpload/" + __version__ def do_GET(self): """Serve a GET request.""" f = self.send_head() if f: self.copyfile(f, self.wfile) f.close() def do_HEAD(self): """Serve a HEAD request.""" f = self.send_head() if f: f.close() def do_POST(self): """Serve a POST request.""" r, info = self.deal_post_data() print r, info, "by: ", self.client_address f = StringIO() f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">') f.write("<html>\n<title>Upload Result Page</title>\n") f.write("<body>\n<h2>Upload Result Page</h2>\n") f.write("<hr>\n") if r: f.write("<strong>Success:</strong>") else: f.write("<strong>Failed:</strong>") f.write(info) f.write("<br><a href=\"%s\">back</a>" % self.headers['referer']) f.write("<hr><small>Powered By: bones7456, check new version at ") f.write("<a href=\"http://luy.li/?s=SimpleHTTPServerWithUpload\">") f.write("here</a>.</small></body>\n</html>\n") length = f.tell() f.seek(0) self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(length)) self.end_headers() if f: self.copyfile(f, self.wfile) f.close() def deal_post_data(self): boundary = self.headers.plisttext.split("=")[1] remainbytes = int(self.headers['content-length']) line = self.rfile.readline() remainbytes -= len(line) if not boundary in line: return (False, "Content NOT begin with boundary") line = self.rfile.readline() remainbytes -= len(line) fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line) if not fn: return (False, "Can't find out file name...") path = self.translate_path(self.path) fn = os.path.join(path, fn[0]) while os.path.exists(fn): fn += "_" line = self.rfile.readline() remainbytes -= len(line) line = self.rfile.readline() remainbytes -= len(line) try: out = open(fn, 'wb') except IOError: return (False, "Can't create file to write, do you have permission to write?") preline = self.rfile.readline() remainbytes -= len(preline) while remainbytes > 0: line = self.rfile.readline() remainbytes -= len(line) if boundary in line: preline = preline[0:-1] if preline.endswith('\r'): preline = preline[0:-1] out.write(preline) out.close() return (True, "File '%s' upload success!" % fn) else: out.write(preline) preline = line return (False, "Unexpect Ends of data.") def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing further to do. """ path = self.translate_path(self.path) f = None if os.path.isdir(path): if not self.path.endswith('/'): # redirect browser - doing basically what apache does self.send_response(301) self.send_header("Location", self.path + "/") self.end_headers() return None for index in "index.html", "index.htm": index = os.path.join(path, index) if os.path.exists(index): path = index break else: return self.list_directory(path) ctype = self.guess_type(path) try: # Always read in binary mode. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! f = open(path, 'rb') except IOError: self.send_error(404, "File not found") return None self.send_response(200) self.send_header("Content-type", ctype) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs[6])) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() return f def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ try: list = os.listdir(path) except os.error: self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) f = StringIO() displaypath = cgi.escape(urllib.unquote(self.path)) f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">') f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath) f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath) f.write("<hr>\n") f.write("<form ENCTYPE=\"multipart/form-data\" method=\"post\">") f.write("<input name=\"file\" type=\"file\"/>") f.write("<input type=\"submit\" value=\"upload\"/></form>\n") f.write("<hr>\n<ul>\n") for name in list: fullname = os.path.join(path, name) displayname = linkname = name # Append / for directories or @ for symbolic links if os.path.isdir(fullname): displayname = name + "/" linkname = name + "/" if os.path.islink(fullname): displayname = name + "@" # Note: a link to a directory displays with @ and links with / f.write('<li><a href="%s">%s</a>\n' % (urllib.quote(linkname), cgi.escape(displayname))) f.write("</ul>\n<hr>\n</body>\n</html>\n") length = f.tell() f.seek(0) self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(length)) self.end_headers() return f def translate_path(self, path): """Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.) """ # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] path = posixpath.normpath(urllib.unquote(path)) words = path.split('/') words = filter(None, words) path = os.getcwd() for word in words: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir): continue path = os.path.join(path, word) return path def copyfile(self, source, outputfile): """Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well. """ shutil.copyfileobj(source, outputfile) def guess_type(self, path): """Guess the type of a file. Argument is a PATH (a filename). Return value is a string of the form type/subtype, usable for a MIME Content-type header. The default implementation looks the file's extension up in the table self.extensions_map, using application/octet-stream as a default; however it would be permissible (if slow) to look inside the data to make a better guess. """ base, ext = posixpath.splitext(path) if ext in self.extensions_map: return self.extensions_map[ext] ext = ext.lower() if ext in self.extensions_map: return self.extensions_map[ext] else: return self.extensions_map[''] if not mimetypes.inited: mimetypes.init() # try to read system mime.types extensions_map = mimetypes.types_map.copy() extensions_map.update({ '': 'application/octet-stream', # Default '.py': 'text/plain', '.c': 'text/plain', '.h': 'text/plain', }) def test(Port, HandlerClass = SimpleHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): # BaseHTTPServer.test(HandlerClass, ServerClass) server_address = ('', Port) httpd = ServerClass(server_address, HandlerClass) httpd.serve_forever() if __name__ == '__main__': port = 8000 if len(sys.argv) > 1: port = int(sys.argv[1]) test(port)
无依赖单文件http-ftp文件服务器(py2)的更多相关文章
- gitea 源码阅读笔记 002 生成无依赖单文件可执行包
gitea bindata static gitea 可以通过 make generate 生成一个单文件可执行程序, 该文件不需要任何其它依赖,直接可以单独执行. 对于用户的安装.升级和生成dock ...
- 多线程下载文件,ftp文件服务器
1: 多线程下载文件 package com.li.multiplyThread; import org.apache.commons.lang3.exception.ExceptionUtils; ...
- Ueditor1.4.3实现跨域上传到独立文件服务器,完美解决单文件和多文件上传!
再写配置方法之前先吐槽一下网上的各种教程,TM没一个有卵用,一群傻屌不会写就别写,写了就要负责. 百度google搜了半天,全是配置什么document.domain,根域名什么的,我只想对你说: 好 ...
- java-压缩文件成zip文件(多文件/单文件/多目录/单目录/无目录),用于下载
本博客是自己在学习和工作途中的积累与总结,仅供自己参考,也欢迎大家转载,转载时请注明出处. http://www.cnblogs.com/king-xg/p/6424788.html 上代码: pac ...
- 开源作品-PHP写的在线文件管理工具(单文件绿色版)-SuExplorer_PHP_3_0
前言:项目开发过程中,网站一般部署到远程服务器,所以文件管理就不能和本机操作一样方便.通常文件管理是用ftp下载到本地,修改后再上传,或者远程登录到服务器进行修改.但是这些操作都依赖于复杂的第三方软件 ...
- 上传图片,多图上传,预览功能,js原生无依赖
最近很好奇前端的文件上传功能,因为公司要求做一个支持图片预览的图片上传插件,所以自己搜了很多相关的插件,虽然功能很多,但有些地方不能根据公司的想法去修改,而且需要依赖jQuery或Bootstrap库 ...
- 开源作品-PHP写的Redis管理工具(单文件绿色版)-SuRedisAdmin_PHP_1_0
前言:项目开发用到了Redis,但是在调试Redis数据的时候,没有一款通用的可视化管理工具.在网络找了一些,但是感觉功能上都不尽人意,于是决定抽出一点时间,开发一个用起来顺手的Redis管理工具.秉 ...
- 开源作品-PHP写的JS和CSS文件压缩利器(单文件绿色版)-SuMinify_PHP_1_5
前言: 网站项目需要引用外部文件以减小加载流量,而且第一次加载外部资源文件后,其他同域名的页面如果引用相同的地址,可以利用浏览器缓存直接读取本地缓存资源文件,而不需要每个页面都下载相同的外部资源文件. ...
- 开源作品-ThinkPHP在线分析工具(单文件绿色版)-TPLogAnalysis_PHP_1_0
TPLogAnalysis_PHP_1_0 前言:项目开发基于ThinkPHP框架,但是在调试程序的时候,没有一款日志可视化分析工具.在网络也找不到任何相关的TP日志分析工具.求人不如求己,于是决定抽 ...
随机推荐
- mssql sqlserver 如何编写case when 多条件呢?
摘要: 下文讲述case when中多条件的编写方法,如下所示: 实验环境:sql server 2008 R2 case when 多条件编写方法 case when多条件编写语法: case ...
- shiro授权、注解式开发
在ShiroUserMapper.xml中新增内容 <select id="getRolesByUserId" resultType="java.lang.Stri ...
- Codeforces Round #608 (Div. 2)
传送门 A. Suits 签到. Code /* * Author: heyuhhh * Created Time: 2019/12/15 17:16:33 */ #include <iostr ...
- 0day2安全——笔记2
第二章 内存的不同用途 windows应用—>编译连接—>PE文件—>进程 进程使用的内存 1.代码区:储存着被装入执行的二进制机器代码,处理器会到这个区域取指和执行 2.数据区:用 ...
- 201871010108-高文利《面向对象程序设计(java)》第十四周学习总结
项目 内容 这个作业属于哪个课程 <任课教师博客主页链接> https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 <作业链接地址> ht ...
- Codeforces Round #598 (Div. 3) B. Minimize the Permutation 贪心
B. Minimize the Permutation You are given a permutation of length n. Recall that the permutation is ...
- ASP.NET Core 集成测试中模拟登录用户的一种姿势
不管哪种用户验证方式,最终都是在验证成功后设置 HttpContext.User ,后续处理环节通过 HttpContext.User 获取用户信息.如果能直接修改 HttpContext.User ...
- PHP实现Redis分布式锁
锁在我们的日常开发可谓用得比较多.通常用来解决资源并发的问题.特别是多机集群情况下,资源争抢的问题.但是,很多新手在锁的处理上常常会犯一些问题.今天我们来深入理解锁. 一.Redis 锁错误使用之一 ...
- php time() 和 $_SERVER['REQUEST_TIME']
time() 和 $_SERVER['REQUEST_TIME']效率 结果:(其中之一) 结论: time() : 执行时间在0.10 - 0.30 之间 $_SERVER['REQUEST_TIM ...
- jemalloc内存占用问题
最近,有部分越南的服务器内存不断上涨,怀疑是内存泄漏,因为框架提供的内存报告里,C内存和Lua占用内存都不大,和ps里看的差好多.总内存在12G左右,C和Lua的加起来约4G,两者相差了8G 经过一番 ...