开发机Python HTTP服务器

2023-05-16

目录下执行下载py文件,

wget http://10.138.59.50:8080/HttpServer.py

执行,

nohup python2 HttpServer.py 8081 &

浏览器打开 ip:8081

我的开发是:XXX.XXX.XXX.XXX
故,
XXX.XXX.XXX.XXX:8081

HttpServer.py这个python脚本的内容为,

#!/usr/bin/env python
#coding=utf-8
# modifyDate: 20120808 ~ 20120810
# 原作者为:bones7456, http://li2z.cn/
# 修改者为:decli@qq.com
# v1.2,changeLog:
# +: 文件日期/时间/颜色显示、多线程支持、主页跳转
# -: 解决不同浏览器下上传文件名乱码问题:仅IE,其它浏览器暂时没处理。
# -: 一些路径显示的bug,主要是 cgi.escape() 转义问题
# ?: notepad++ 下直接编译的server路径问题
  
"""
  简介:这是一个 python 写的轻量级的文件共享服务器(基于内置的SimpleHTTPServer模块),
  支持文件上传下载,只要你安装了python(建议版本2.6~2.7,不支持3.x),
  然后去到想要共享的目录下,执行:
    python SimpleHTTPServerWithUpload.py 1234    
  其中1234为你指定的端口号,如不写,默认为 8080
  然后访问 http://localhost:1234 即可,localhost 或者 1234 请酌情替换。
"""
  
"""Simple HTTP Server With Upload.
  
This module builds on BaseHTTPServer by implementing the standard GET
and HEAD requests in a fairly straightforward manner.
  
"""
  
__version__ = "0.1"
__all__ = ["SimpleHTTPRequestHandler"]
__author__ = "bones7456"
__home_page__ = ""
  
import os, sys, platform
import posixpath
import BaseHTTPServer
from SocketServer import ThreadingMixIn
import threading
import urllib, urllib2
import cgi
import shutil
import mimetypes
import re
import time
  
try:
  from cStringIO import StringIO
except ImportError:
  from StringIO import StringIO
    
def get_ip_address(ifname):
  import socket
  import fcntl
  import struct
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  return socket.inet_ntoa(fcntl.ioctl(
    s.fileno(),
    0x8915, # SIOCGIFADDR
    struct.pack('256s', ifname[:15])
  )[20:24])
  
class GetWanIp:
  def getip(self):
    try:
      myip = self.visit("www.taobao.com")
    except:
      print "ip.taobao.com is Error"
      try:
        myip = self.visit("http://www.bliao.com/ip.phtml")
      except:
        print "bliao.com is Error"
        try:
          myip = self.visit("http://www.whereismyip.com/")
        except: # 'NoneType' object has no attribute 'group'
          print "whereismyip is Error"
          myip = "127.0.0.1"
    return myip
  def visit(self,url):
    #req = urllib2.Request(url)
    #values = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537',
    #      'Referer': 'http://ip.taobao.com/ipSearch.php',
    #      'ip': 'myip'
    #     }
    #data = urllib.urlencode(values)
    opener = urllib2.urlopen(url, None, 3)
    if url == opener.geturl():
      str = opener.read()
    return re.search('(\d+\.){3}\d+',str).group(0)
  
def showTips():
  print ""
  print '----------------------------------------------------------------------->> '
  try: 
    port = int(sys.argv[1])
  except Exception, e:
    print '-------->> Warning: Port is not given, will use deafult port: 8080 '
    print '-------->> if you want to use other port, please execute: '
    print '-------->> python SimpleHTTPServerWithUpload.py port '
    print "-------->> port is a integer and it's range: 1024 < port < 65535 "
    port = 8080
    
  if not 1024 < port < 65535: port = 8080
  # serveraddr = ('', port)
  print '-------->> Now, listening at port ' + str(port) + ' ...'
  osType = platform.system()
  if osType == "Linux":
    print '-------->> You can visit the URL:   http://'+ GetWanIp().getip() + ':' +str(port)
  else:
    print '-------->> You can visit the URL:   http://127.0.0.1:' +str(port)
  print '----------------------------------------------------------------------->> '
  print ""
  return ('', port)
  
serveraddr = showTips()  
  
def sizeof_fmt(num):
  for x in ['bytes','KB','MB','GB']:
    if num < 1024.0:
      return "%3.1f%s" % (num, x)
    num /= 1024.0
  return "%3.1f%s" % (num, 'TB')
  
def modification_date(filename):
  # t = os.path.getmtime(filename)
  # return datetime.datetime.fromtimestamp(t)
  return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(filename)))
  
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."""
    # print "....................", threading.currentThread().getName()
    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://li2z.cn/?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)
    osType = platform.system()
    try:
      if osType == "Linux":
        fn = os.path.join(path, fn[0].decode('gbk').encode('utf-8')) 
      else:
        fn = os.path.join(path, fn[0]) 
    except Exception, e:
      return (False, "文件名请不要用中文,或者使用IE上传中文名的文件。")
    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\"/>")
    f.write("              ")
    f.write("<input type=\"button\" value=\"HomePage\" onClick=\"location='/'\">")
    f.write("</form>\n")
    f.write("<hr>\n<ul>\n")
    for name in list:
      fullname = os.path.join(path, name)
      colorName = displayname = linkname = name
      # Append / for directories or @ for symbolic links
      if os.path.isdir(fullname):
        colorName = '<span style="background-color: #CEFFCE;">' + name + '/</span>'
        displayname = name
        linkname = name + "/"
      if os.path.islink(fullname):
        colorName = '<span style="background-color: #FFBFFF;">' + name + '@</span>'
        displayname = name
        # Note: a link to a directory displays with @ and links with /
      filename = os.getcwd() + '/' + displaypath + displayname
      f.write('<table><tr><td width="60%%"><a href="%s">%s</a></td><td width="20%%">%s</td><td width="20%%">%s</td></tr>\n'
          % (urllib.quote(linkname), colorName, 
            sizeof_fmt(os.path.getsize(filename)), modification_date(filename)))
    f.write("</table>\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',
    '.log': 'text/plain'
    })
  
class ThreadingServer(ThreadingMixIn, BaseHTTPServer.HTTPServer):
  pass
    
def test(HandlerClass = SimpleHTTPRequestHandler,
    ServerClass = BaseHTTPServer.HTTPServer):
  BaseHTTPServer.test(HandlerClass, ServerClass)
  
if __name__ == '__main__':
  # test()
    
  #单线程
  # srvr = BaseHTTPServer.HTTPServer(serveraddr, SimpleHTTPRequestHandler)
    
  #多线程
  srvr = ThreadingServer(serveraddr, SimpleHTTPRequestHandler)
    
  srvr.serve_forever()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

开发机Python HTTP服务器 的相关文章

  • 【ROS Rikirobot基础-使用系列 第四章节】Rikirobot小车使用激光雷达进行自动导航

    利用激光雷达进行自动导航 这里我们教大家使用的是利用激光雷达导航 xff0c 关于深度摄像头的导航我们后面会教大家使用 1 上电启动小车 xff0c 主控端执行启动小车的命令 xff1a roslaunch rikirobot bringu
  • js函数的四种调用形式以及this的指向

    以函数的 形式调用 xff1a function fun alert this 61 61 window fun 调用成功 xff0c this代表window 以方法的形式调用 var obj 61 name 61 34 hello 34
  • warning: control reaches end of non-void function

    用gcc编译一个程序的时候出现这样的警告 xff1a warning control reaches end of non void function 它的意思是 xff1a 控制到达非void函数的结尾 就是说你的一些本应带有返回值的函数
  • 项目中遇到的问题及解决方案

    1 用到的视频播放插件只支持加载相对路径 xff0c 不能加载绝对路径上的资源 解决方案 xff1a 为tomca t配置 文件 创建索引 xff0c 在 server xml文件中增加配置 lt Context path 61 34 IM
  • Oracle批量更新sql写法

    select from test table for update begin for cur in select id from test table loop update test table set name 61 39 苏晓伟 3
  • JVM 垃圾回收机制

    JVM体系结构概览 xff1a 垃圾回收 xff08 GC xff09 发生在哪个区 xff1a heap xff08 堆 xff09 区 GC是什么 xff1f 分几种 xff1a GC 分代收集算法 次数上频繁收集young区 xff0
  • JAVA 自定义注解

    多说无益 xff0c 直接上代码 import java lang annotation Documented import java lang annotation ElementType import java lang annotat
  • Vuex 学习

    什么是vuex xff1a 专门在Vue中实现集中式状态 xff08 数据 xff09 管理的一个Vue插件 xff0c 对vue应用中多个组件的共享状态进行集中式的管理 xff08 读 写 xff09 xff0c 也是一种组件间通信的方式
  • zookeeper本地安装启动

    下载zookeeper xff1a 链接 xff1a https pan baidu com s 151ZdXYg6QDB A8TRK0wrpw 提取码 xff1a yyds 复制到linux上并解压修改配置文件的名字 xff0c 将 zo
  • zookeeper集群安装

    准备3台服务器 xff0c 安装三个zookeeper xff0c 修改zoo cfg配置 xff0c dataDir 61 opt module zookeeper 3 5 7 zkData 分别在zkData目录下创建一个文件myid
  • zookeeper 启动停止脚本

    bin bash case 1 in 34 start 34 for i in 192 168 66 133 192 168 66 134 192 168 66 129 do echo zookeeper i 启动 ssh i 34 opt
  • ElasticSearch-全文检索

    docker 下载安装 es镜像 docker pull elasticsearch 7 4 2 es的可视化工具 docker pull kibana 7 4 2 mkdir p mydata elasticsearch config m
  • atoi()和stoi()的区别----数字字符串的处理

    相同点 xff1a 都是C 43 43 的字符处理函数 xff0c 把数字字符串转换成int输出 头文件都是 include lt cstring gt 不同点 xff1a atoi 的参数是 const char 因此对于一个字符串str
  • ROS基础教程--CostMap_2D包的一些理解

    本文是在综合了多篇文章的基础之上进行的综合 1 基本概念 Voxel xff1a 体素 xff0c 即顾名思义是体积的像素 用来在三维空间中表示一个显示基本点的单位 类似于二维平面下的pixel xff08 像素 xff09 voxel是三
  • [move_base-24] process has died [exit code -6, cmd lib/move_base/move_base odom:=mobile_base_control

    尝试使用TIAGo机器人进行SLAM时 xff0c 运行 roslaunch tiago 2dnav gazebo tiago mapping launch public sim 61 true 指令时加载TIAGo机器人失败 xff0c
  • geoserver集群搭建及数据共享设置

    Geoserver版本及所需依赖 geoserver 2 16 0geoserver 2 16 SNAPSHOT jms cluster plugingeoserver 2 16 SNAPSHOT activeMQ broker plugi
  • postgresql 9.5 now()函数少8小时

    select now 时获取的时间比系统时间少8小时 xff0c 时区问题 xff0c 可能是postgresql conf中的log timezone timezone没有配置成 PRC SELECT now AT TIME ZONE 3
  • sld样式文件demo

    标注样式为 xff1a 代码为 xff1a lt xml version 61 34 1 0 34 encoding 61 34 UTF 8 34 gt lt StyledLayerDescriptor xmlns 61 34 http w
  • 清理Linux buffer/cache内存的方法

    解决Linux buffer cache内存占用过高的办法 xff08 转载 xff09 Linux中Cache内存占用过高解决办法 xff08 转载 xff09
  • windows10下修改Docker镜像目录

    1 背景需求 Windows 版本 xff08 Windows 10 wsl 2 xff09 docker 默认程序安装到c盘 xff0c 数据存储于C Users 当前用户名 AppData Local Docker wsl data e

随机推荐