`
kenby
  • 浏览: 715534 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Virtualbox下Windows和Linux实现文件互传

 
阅读更多

1 Windows安装好Linux虚拟机

 

2 在Linux下运行一个 Python 实现的http服务器,代码如下:

 

 

#!/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.

"""


__version__ = "0.1"
__all__ = ["SimpleHTTPRequestHandler"]
__author__ = "bones7456"
__home_page__ = "http://li2z.cn/"

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://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)
        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(HandlerClass = SimpleHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)

if __name__ == '__main__':
    test()

 

 

运行:python SimpleHttpServer.py 8000

 

 

3 设置Virtualbox的连接方式为 NAT,并做好端口映射:


 

 

4 在 Windows 下,浏览器输入 http://127.0.0.1:8000 就可以上传和下载 Linux下的文件


 

  • 大小: 55.3 KB
分享到:
评论

相关推荐

    Virtualbox主机和虚拟机之间文件夹共享及双向拷贝(Windows&lt;-&gt;Windows, Windows&lt;-&gt;Linux)

    本篇文章主要是介绍了Virtualbox主机和虚拟机之间文件夹共享及双向拷贝,有需要的可以了解一下。

    VirtualBox与Windows文件夹共享

    设置后,Windows下的文件夹被映像到Virtualbox Linux下,在Virtualbox下访问该文件夹就像打开本地文件夹一样,不用使用FTP等外界工具实行跳转,实现了在Windows下与Virtualbox相互共享文件。

    VirtualBox内Linux系统怎样与Windows共享文件夹

    VirtualBox内Linux系统怎样与Windows共享文件夹

    VirtualBox-6.0.20-137117-Win.exe

    Oracle VM VirtualBox VirtualBox 是针对基于 x86 的系统的强大的跨平台虚拟化软件。 “跨平台”意味着它可以... Oracle VM VirtualBox 以 Windows、Linux、Mac OS X 和 Solaris 的开源或预构建二进制文件的形式提供。

    VirtualBox软件下载安装及Linux环境安装部署

    VirtualBox软件下载安装及Linux环境安装部署 一、VirtualBox软件下载及安装 首先进入VirtualBox官方网站进行软件下载, https://www.virtualbox.org/,目前VirtualBox最新的版本为6.1,详细如下图: 点击...

    虚拟机virtualbox.rar

    它简单易用,可虚拟的系统包括Windows(从Windows 3.1到Windows10、Windows Server 2012,所有的Windows系统都支持)、Mac OS X、Linux、OpenBSD、Solaris、IBM OS2甚至Android等操作系统!使用者可以在VirtualBox上...

    VirtualBox软件下载安装及Linux环境安装部署图文教程详解

    一、VirtualBox软件下载及安装 首先进入VirtualBox官方网站进行软件...双击“VirtualBox-6.1.4-136177-Win.exe”文件进行安装,详细见下图 点击“下一步”按钮进行安装 默认安装路径为“C:\Program Files\Oracle\V

    VirtualBox创建的Debian虚拟机与Windows宿主共享文件

    1、在Windows10上下载并安装VirtualBox6.0.8(时间:2019/5/30),下载地址:https://download.virtualbox.org/virtualbox/6.0.8/VirtualBox-6.0.8-130520-Win.exe 或者https://www.virtualbox.org/wiki/Downloads另选...

    virtualBox(虚拟机)中文版 v 5.1.18.zip

    VirtualBox是一款免费的开源虚拟机,它简单易用,支持Windows、Linux和Mac系统主机,可虚拟的系统包括Windows (NT 4.0、2000、XP、Server 2003、Vista、Win7、Win8)、DOS/Windows 3.x、Linux (2.4和2.6)、OpenBSD等...

    LINUX基本操作(1)

    ② 浏览/usr目录下所有文件列表,包含隐含文件以及文件详细权限信息,区分文件和目录的区别。 ③ 用pwd命令显示当前工作目录 ④ 使用命令将“I love os”写到file1.txt文件里,然后使用命令读出文件里的内容。 .....

    VMware Tools-Linux.tar

    VMware Tools是VMware虚拟机中自带的一种增强工具,相当于VirtualBox中的增强功能(Sun VirtualBox Guest Additions),是VMware提供的增强虚拟显卡和硬盘性能、以及同步虚拟机与主机时钟的驱动程序。 只有在VMware...

    VirtualBox 共享文件夹权限设置及使用方法

    VirtualBox 共享文件夹权限设置及使用方法 ... 共享文件夹就是使主机的wendows和客户机linux能彼此共享文件。在当前的架构情况下,需要在主机即windows上设一个目录来做共享目录,我是把D盘的sharedfolde

    windows docker环境设置注意事项

    windows docker环境设置 1、下载docker-install.exe安装VirtualBox、Git、Boot2Docker for Windows 2、设置环境变量,启动boot2docker ...4、通过设置VirtualBox的共享目录,实现windows和docker之间的文件互传。 5、在

    VirtualBox 共享文件夹设置及开机自动挂载详细教程

    鉴于支付宝等服务无视我们Linux用户的存在,没办法,那只好在Linux上用VirtualBox 虚拟一个Windows系统了。系统装好了,在日常使用过程中,往往要从VirtualBox的客户机(guest system)中使用主机(host system)...

    virtualbox4.2

    windows工具,可以在Windows上连接linux服务器,上传文件

    linux Shell获取某目录下所有文件夹的名称

    查看目录下面的所有文件: #!/bin/bash cd /目标目录 for file in $(ls *) do echo $file done ... 您可能感兴趣的文章:Virtualbox主机和虚拟机之间文件夹共享及双向拷贝(Windows&lt;-&gt;Windows, Win

    Linux学习笔记

    CentOS 6 安装VirtualBox客户端增强功能、Windows 7同 Linux双启动、修复Windows 7系统MBR、常用配置文件、Linux终端乱码的解决办法

    eoan server cloudimg amd64 vagrant虚拟机VirtualBox亲测可用

    Ubuntu是一个可将PC和物联网设备连接到服务器和云的平台。包含了一整套用于开发,配置,管理和服务编排的企业级工具。自Ubuntu第一个版本Ubuntu 4.10 (代号Warty Warthog)...支持Linux、Windows、Mac OS等系统环境。

    VMware-tools-10.3.10-12406962-x86_64.exe

    VMware Tools是一款VMware Workstation 虚拟机软件的增强工具包,相当于VirtualBox中的增强功能(Sun VirtualBox Guest Additions),是VMware提供的增强虚拟显卡和硬盘性能、以及同步虚拟机与主机文件的驱动程序。...

    VBox Raw Disk GUI:VirtualBox 命令 createrawvmdk 的 GUI-开源

    适用于 Windows 和 Linux,但应该适用于 Mac、BSD 等,前提是 VirtualBox 和 Java 工作正常,并且命令针对您正在运行的操作系统进行了更新。 -- 变更日志 -- 2017-12-05 - 2.7 版本发布! (修复/重写Windows磁盘...

Global site tag (gtag.js) - Google Analytics