无依赖单文件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日志分析工具.求人不如求己,于是决定抽 ...
随机推荐
- 点击element-ui表格中的图标,上方显示具体的文字描述
<template> <el-table :data="tableData" style="width: 100%"> <el-t ...
- 《算法问题实战策略》 BOGGLE
oj地址是韩国网站 连接比较慢 https://algospot.com/judge/problem/read/BOGGLE大意如下 输入输出 输入 URLPM XPRET GIAET XTNZY X ...
- 给那些迷茫的人学习JAVA的一些建议?
前语:我用了3年的时间,一步一步走到了现在,半途也有了解过其他的技能,也想过要转其他的言语,可是最终仍是坚持下来走Java这条路,希望我的经历能够帮忙到后来的人,要是觉得对你有帮忙的话,能够注重一下和 ...
- 图书分享 -《Natural Language Processing with Python》
-<Natural Language Processing with Python> 链接:https://pan.baidu.com/s/1_oalRiUEw6bXbm2dy5q_0Q ...
- 推荐|MathType的使用技巧
前言 持续更新中,敬请期待... 数学学科 制作新的数学符号 不包含于符号:输入$\not\subseteq,然后按回车键enter即可: 分式\(\cfrac{3-x}{2x-1}\)符号:输入$\ ...
- 【51Nod1769】Clarke and math2(数论,组合数学)
[51Nod1769]Clarke and math2(数论,组合数学) 题面 51Nod 题解 考虑枚举一个\(i_k\),枚举一个\(i\),怎么计算\(i_k\)对\(i\)的贡献. 把\(\f ...
- 几个高逼格 Linux 命令!
作者:忧郁巫师 https://dwz.cn/A1FOjLXk 1. sl 命令 你会看到一辆火车从屏幕右边开往左边…… 安装 $ sudo apt-get install sl 运行 $ sl 命令 ...
- c# winform 窗体失去焦点关闭(钩子实现)
先来一个辅助类 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Inte ...
- MySQL GROUP BY 的问题
拿 employee 示例数据库为例,当进行如下操作时会报错. mysql> SELECT * FROM employees GROUP BY gender; ERROR 1055 (42000 ...
- PlayJava Day005
今日所学: /* 2019.08.19开始学习,此为补档. */ 类:一类事物的抽象体(如全人类,学生类,订单类) 对象:具体的个体(如张三,某个外卖订单) 对象具有属性和行为. 声明的属性语句一般放 ...