`
kenby
  • 浏览: 724567 次
  • 性别: 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)

    在Windows系统主机与Windows系统虚拟机之间共享文件夹时,需要在Virtualbox的“设备”菜单中进行设置,选择“分配光驱”,然后加载VirtualBox安装目录下的VBoxGuestAdditions.iso文件。接下来,在虚拟机中运行...

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

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

    windows模拟linux系统传文件工具Csdnmjfxz

    6. **rsync命令**:rsync是Linux下的数据同步工具,通常配合SSH使用,可以实现增量备份和快速同步文件。在Windows上,可以借助Cygwin或者WSL(Windows Subsystem for Linux)来使用rsync命令。 7. **WSL(Windows ...

    在windows上安装VirtualBox虚拟机以及linux环境搭建

    在Windows操作系统上安装VirtualBox虚拟机以及搭建Linux环境,是一个常见的多系统共存的解决方案,尤其对于开发者和学习者来说,能方便地在不改变主机系统的情况下体验和操作不同的操作系统。以下将详细介绍整个过程...

    在Win7下用Virtualbox虚拟机安装RedHat Linux系统

    通过本文所述的步骤,可以在Windows 7环境下使用VirtualBox成功地安装Red Hat Linux系统。虽然过程中可能遇到一些常见的技术障碍,但只要遵循正确的步骤和注意事项,大多数问题都可以得到解决。希望本文能够帮助那些...

    如何在Windows下给linux杀毒,查杀Linux恶意文件.zip

    下面将详细讨论如何在Windows环境下对Linux系统进行恶意文件的检测和清除。 首先,我们需要理解的是,由于Linux和Windows是两种不同的操作系统,它们的文件系统结构和执行机制各有不同,因此常规的Windows杀毒软件...

    Oracle VM VirtualBox 安装 Linux

    VirtualBox 可在 Windows、Linux、Mac OS X 和 Solaris 等操作系统上运行,并支持在虚拟机中安装各种类型的客户操作系统,包括但不限于 Windows、Linux、Solaris、OpenBSD 等。 #### 二、安装 Linux 的原因与应用...

    VirtualBox安装以及部署windows 2008虚拟机教程

    VirtualBox是一款开源、跨平台的虚拟化软件,它提供了高效且强大的虚拟化环境,使得用户可以在Windows、Linux、Mac OS X等多种操作系统上安装和运行其他操作系统,如Windows 2008。下面我们将详细探讨VirtualBox的...

    VirtualBox与Windows文件夹共享

    为了简化这一过程,提高工作效率,我们可以利用VirtualBox提供的文件夹共享功能实现Windows与Linux间的无缝文件交换。 #### 二、基础知识 1. **VirtualBox**:一款开源虚拟机软件,可以在一个操作系统上运行多个...

    在Windows下轻松读写Linux分区.pdf

    《在Windows下轻松读写Linux分区》这篇文档主要聚焦于如何在Windows环境下访问和操作Linux文件系统,这对于那些同时使用Windows和Linux双系统的用户来说,是一个极具实用价值的主题。Linux分区通常采用EXT2、EXT3、...

    在VirtualBox中向Debian Linux移植通达OA2008.docx

    通过上述步骤,不仅能够在VirtualBox中成功搭建一个模拟的内部网络环境,还能将原本运行在Windows环境下的通达OA2008迁移到Debian Linux上,从而达到学习和理解Linux、MySQL、Apache、PHP等技术的目的。此外,还可以...

    使用VirtualBox在Windows上安装和使用OpenSolaris的例子.docx

    ### 使用VirtualBox在Windows上安装和使用OpenSolaris的知识点 #### 一、VirtualBox的介绍与安装 **VirtualBox**是一种开源的虚拟机管理软件,由Oracle公司维护。它能够在单台计算机上同时运行多个操作系统,使得...

    虚拟机Linux下实现文件夹共享

    ### 虚拟机Linux下实现文件夹共享 #### 知识点概览 1. **虚拟机概念与原理** 2. **Linux操作系统基础** 3. **虚拟机中Linux文件共享的方法** 4. **配置虚拟机共享文件夹的步骤详解** #### 知识点详细解释 **1. ...

    在windows下如何备份linux分区.zip

    - 使用支持Linux文件系统的工具(如GParted Live、SystemRescueCD等)创建启动媒体。 - 在Windows系统下,通过USB或DVD启动这个媒体,进入救援或Live环境。 - 使用备份工具创建Linux分区的映像文件,保存到外部...

    Windows网络下的Linux解决方案

    9. **网络服务互操作**:例如DNS、DHCP和NTP等服务,通过标准协议实现Windows和Linux服务器之间的协同工作。 10. **安全与认证**:Kerberos是一种广泛使用的网络认证协议,支持Windows Active Directory和Linux系统...

    windows 版VirtualBox-6.0.10-132072.zip

    7. **共享文件夹和网络设置**:VirtualBox允许用户设置共享文件夹,实现主机和虚拟机之间的文件交换,以及网络连接模式(如桥接网络、NAT网络等),以满足不同应用场景的需求。 8. **扩展功能**:通过VirtualBox的...

    Linux下VirtualBox安装

    Linux 下 VirtualBox 安装及多虚拟 IP 创建 本文档将指导您在 RedHat Linux 5.3 系统中安装 VirtualBox 及创建多个虚拟 IP。VirtualBox 是一款功能强大且流行的虚拟机软件,能够在单台机器上运行多个虚拟机,从而...

    VirtualBox-6.0.20-137117-Win.exe

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

    在XP 安装VirtualBox 搭建Linux 系统

    此外,通过配置共享文件夹,用户能够在Windows和Linux之间高效地传输文件,极大地提高了工作效率。 这种方式的主要优点包括: - Windows和Linux之间的快速切换,无需重启计算机。 - Linux系统避免了可能遇到的兼容...

    虚拟机(Virtualbox-Ubuntu)与主机(WIN7)共享文件夹设置

    本文将详细介绍如何在Virtualbox环境下配置Ubuntu虚拟机与Windows 7主机之间的共享文件夹。 #### 二、环境配置 - **主机系统**:Windows 7 32位旗舰版 - **虚拟机平台**:Sun VirtualBox 4.0.4 - **客户机系统**:...

Global site tag (gtag.js) - Google Analytics