# VirtualBox Extras (简体中文)

## 配置

### 网络

VirtualBox 客户端可以通过不同的方式连接网络；其中，有#NAT和#桥接链接。#NAT是最简单的且作为一个新虚拟机的默认方式。

VirtualBox手册涵盖了主机模式和内网选项。这些都被忽略了，因为在大多数情况下与操作系统无关。

#### NAT

在VirtualBox中：

- 访问虚拟机的设置菜单；
- 点击左边的网络‘’；最后，
- 在“连接方式”的下拉列表中选择NAT。

与VirtualBox捆绑的DHCP服务使得客户端系统能够与DHCP一起配置，第一张卡的NAT IP地址是 10.0.2.0，第二张是10.0.3.0，往后以此类推。

#### 桥接

桥接网络可能被以多种方式启动；其中，有要求以较少控制为代价进行最小启动的原生方式。对于较新版本，VirtualBox可以在没有第三方工具的帮助下，在客户端和无线主机接口间进行桥接。

在继续之前，加载必要模块：

    # modprobe vboxnetflt

在VirtualBox中：

- 访问虚拟机的设置菜单；
- 点击左边列表中的网络
- 在链接方式的下拉列表中选择Bridged Adapter(桥接适配器)；最后，
- 在界面名称下拉列表中，选择客户端操作系统被包含在内，主机用于连接网络的接口。

Start the virtual machine and configure its network as usual; e.g., DHCP or static. 打开虚拟机，像往常一样配置其网络；例如 DHCP 或 static（静态网络）。

### 客户端增强包

客户端增强包（The Guest Additions）能够激活共享文件夹功能，改善显卡加速支持和在主机端及客户端之间启用双向剪贴板。鼠标集成是另一项功能，用于减少在客户端中使用鼠标后将其释放的需要。

#### Arch Linux 客户端

参阅Arch Linux VirtualBox客户端

#### Windows 客户端

在你的虚拟机中安装Windows（XP 等等）后，只需选择设备 → 安装增强功能

这将会挂载ISO镜像，接着Windows应该自动运行客户端增强包安装向导（The guest additions installer）。按照说明进行到底。

### 主机端和客户端之间的键盘和鼠标

- 为了捕获键盘和鼠标，点击虚拟机内部。
- 想要释放，按下右 `Ctrl`.

想要获得在主机端和客户端之间的无缝鼠标集成功能，在客户端内安装#客户端增强包。

### 主机端和客户端间的共享文件夹

在虚拟机的设置中，找到数据空间标签，然后加入你想要共享的文件夹。

- 注意：为了使用这个功能你需要安装客户端增强包。

    在Linux主机中，设备 → 安装增强功能
    确定（被要求下载CD镜像时）
    挂载（被要求注册和挂载时）

In a Linux host, create one or more folders for sharing files, then set the shared folders via the virtualbox menu (guest window). 在Linux主机端中，为共享的文件创建一个或更多的文件夹，然后通过Virtualbox菜单中设置（Windows客户端）

在Windows客户端中，从VirtualBox 1.5.0开始，共享文件夹是可浏览的，所以在Windows资源管理器中是可视的。打开Windows资源管理器，在我的网络位置（My Networking Places） → 整个网络（Entire Network） → VirtualBox Shared Folders（VirtualBox共享文件夹）。

启动Windows资源管理器（运行资源管理器命令），游览 网络位置（network places） -> （+）号展开： 整个网络（entire network）&rarr； VirtualBox Shared Folders（VirtualBox共享文件夹） &rarr；\\Vboxsvr → 然后你就可以在此展开所有已配置的文件夹了，并且在客户端文件系统中为Linux文件夹创建快捷方式。你也可以使用“添加网络位置向导（Add network place wizard）”找到“VBoxsvr”。

此外，在Windows命令行提示符中，你也可以使用以下命令：

    net use x: \\VBOXSVR\sharename

虽然`VBOXSVR`是一个固定名称，但请用你所想要用于共享的盘符替代`x:`，用VBoxManage指定的共享名替换sharename。

在Windows客户端中，为了以VirtualBox共享文件夹改善文件的读取与保存（如MS Office），编辑c:\windows\system32\drivers\etc\hosts如下：

    127.0.0.1 localhost vboxsvr

在Linux客户端中，实用以下命令：

    # mount -t vboxsf [-o OPTIONS] sharename mountpoint
      (注意：共享名是任意的，或者和VirtualBox对话框中选定的一样（在主机端文件系统中共享目录的挂载点）。

  自动挂载共享文件夹可以通过Linux客户端 /etc/fstab 文件来实现。你可以指定uid=#,gid=#（# 用实际的数字uid和gid替换），以便以普通用户权限（而不是root权限）来挂载共享文件夹。（这个对于为了在Linux客户端中使用而挂载主机上～/home的一部分是很有用的。为了做到这点，依照以下格式添加一个条目到Linux客户端中的/etc/fstab：

    sharename mountpoint vboxsf uid=#,gid=# 0 0

用在VBoxManage中指定的共享名替换`sharename`，并用你想要共享的路径替换mountpoint（如 /mnt/share）。通常的挂载申请，就是说，如果还没有的话，先创建这个文件夹。注意，如果你已经让VirtualBox“自动挂载”这个共享文件夹，这一步可能就不必了，而且你的文件夹可以在/media 下找到。

除了mount命令提供的标准选项外，以下是可选的：

    iocharset=CHARSET

设置用于I/O操作的字符集（默认utf8），并且：

    convertcp=CHARSET

用于指定用于共享文件夹名称的字符集（默认utf8）

### 在Windows客户端中激活D3D加速

Recent versions of Virtualbox have support for accelerating OpenGL inside guests. This can be enabled with a simple checkbox in the machine's settings, right below where video ram is set, and installing the Virtualbox guest additions. However, most Windows games use Direct3D (part of DirectX), not OpenGL, and are thus not helped by this method. However, it is possible to gain accelerated Direct3D in your Windows guests by borrowing the d3d libraries from Wine, which translate d3d calls into OpenGL, which is then accelerated.

After enabling OpenGL acceleration as described above, go to http://www.nongnu.org/wined3d/ in your Windows guest and grab the "Latest version (Installer):". Reboot the guest into safe mode (press F8 before the Windows screen appears but after the Virtualbox screen disappears), and install wined3d, accepting the defaults during the install. (You may check the box for DirectX 10 support if you like, dont touch anything else.) Reboot back to normal mode and you should have accelerated Direct3D.

Note: This hack may or may not work for some games depending on what hardware checks they make and what parts of D3D they use.
Note: This has only been tried on Windows XP and Windows 7 RC guests AFAIK, and does not work on the Windows 7 guest. If you have experience with this on a different windows version, please add that data here.

### 压缩磁盘映像

#### Linux 客户端

启动Linux客户端并移除所有多余的东西（多余软件包，临时文件等）。满意之后，用dd或更好的dcfldd来擦除空闲空间：

    $ dcfldd if=/dev/zero of=fillfile bs=4M

当填充文件达到了虚拟硬盘的限度，大量的用户空间（非保留块）将会被填满。或者，以Root的身份运行该命令以便填满所有空间。示例信息："8192 blocks (8192Mb) written.dcfldd:: No space left on device."

这种情况下，只需移除填充文件并关闭虚拟机：

    $ rm -f fillfile && sudo shutdown -hF now

注意: 考虑到经过压缩操作， -F 开关将会在重启前强迫磁盘检查。

现在，压缩磁盘：

    $ VBoxManage modifyhd /path/to/your.vdi --compact

## 技巧和窍门

### 获得可探测的Web-cam和其他USB设备

Make sure you filter any devices that are not a keyboard or a mouse so they don't start up at boot and this insures that Windows will detect the device at start-up.

### 向客户端发送CTRL+ALT+F1

如果你的客户端操作系统是Linux发行版，且你又想打开一个新的tty文本shell或者通过键入`Ctrl`+`Alt`+`F1`来退出 X ，你可以简单地敲击你的'Host Key'向客户端操作系统发送这个命令（通常为键盘右边的`Ctrl`） + `F1` 或 `F2`，以此类推。

### 在运行于无显示器的服务器上的系统上启动虚拟机

Add this line to /etc/rc.local

    exec /bin/su -c 'VBoxManage startvm --type headless <UUID|NAME>' PREFERED_USER >/dev/null 2>&1

Where <UUID|NAME> is the guest identifier, and PREFERRED_USER is the user profile that contains the VM definitions and .vdi files.

Since exec replaces the currently running process, you will not be able to start a second VM, or execute any other commands, after the exec. Try the following if this is a problem:

    su -c 'VBoxHeadless -s <UUID|NAME> &' -s /bin/sh PREFERED_USER >/dev/null 2>&1

Using fully qualified path to su and VBoxHeadless is recommend. Add additional lines like above to start additional VMs. Commands following these in rc.local will be executed. Based on some rooting around in the VBox documentation, I get the impression this will be a little more robust than 'VBoxManage ... --type headless' in future VBox releases.

To determine the available VMs for a user:

    su -c 'VBoxManage list vms' PREFERED_USER

To save the state of a running VM:

    su -c 'VBoxManage controlvm <UUID|NAME> savestate' PREFERED_USER

rc.local.shutdown would be a good spot for this.

### 从主机端访问虚拟机上的服务器

To access apache on a VM from the Host machine ONLY, simply execute the following lines on the Host:

    $ VBoxManage setextradata GuestName "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/HostPort" 8888
    $ VBoxManage setextradata GuestName "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/GuestPort" 80
    $ VBoxManage setextradata GuestName "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/Protocol" TCP

Where 8888 is the port the host should listen on and 80 is the port the VM will send Apache's signal on. To use a port lower than 1024 on the host machine changes need to be made to the firewall on the host machine. This can also be set up to work with SSH, etc.. by changing "Apache" to whatever service and using different ports.

Note: "pcnet" refers to the network card of the VM. If you use an Intel card in your VM settings change "pcnet" to "e1000"

- from [1]

It might also be necessary to allow connections from the outside to the server in your VM. E.g. if the guest OS is Arch, you may want to add the line

    httpd: ALL

to your /etc/hosts.allow file.

### 守护进程工具

While VirtualBox can mount ISO images without a problem, there are some image formats which cannot reliably be converted to ISO. For instance, ccd2iso ignores .ccd and .sub files, which can give disk images with broken files. cdemu, fuseiso, and MagicISO will do the same. In this case there is no choice but to use Daemon Tools inside VirtualBox.

Recent Daemon Tools versions won't install, so use this old one: [2]

### 在USB key上使用VirtualBox

When using VirtualBox on a USB key, for example to start an installed machine with an ISO image, you will manually have to create VDMKs from the existing drives. However, once the new VMDKs are saved and you move on to another machine, you may experience problems launching an appropriate machine again. To get rid of this issue, you can use the following script to launch VirtualBox. This script will clean up and unregister old VMDK files and it will create new, proper VMDKs for you:

    #!/bin/bash

    # Erase old VMDK entries
    rm ~/.VirtualBox/*.vmdk

    # Clean up VBox-Registry
    sed -i '/sd/d' ~/.VirtualBox/VirtualBox.xml

    # Remove old harddisks from existing machines
    find ~/.VirtualBox/Machines -name \*.xml | while read file; do
      line=`grep -e "type\=\"HardDisk\"" -n $file | cut -d ':' -f 1`
      if [ -n "$line" ]; then
        sed -i ${line}d $file
        sed -i ${line}d $file
        sed -i ${line}d $file
      fi
      sed -i "/rg/d" $file
    done

    # Delete prev-files created by VirtualBox
    find  ~/.VirtualBox/Machines -name \*-prev -exec rm '{}' \;

    # Recreate VMDKs
    ls -l /dev/disk/by-uuid | cut -d ' ' -f 9,11 | while read ln; do
      if [ -n "$ln" ]; then
        uuid=`echo "$ln" | cut -d ' ' -f 1`
        device=`echo "$ln" | cut -d ' ' -f 2 | cut -d '/' -f 3 | cut -b 1-3`

        # determine whether drive is mounted already
        checkstr1=`mount | grep $uuid`
        checkstr2=`mount | grep $device`
        checkstr3=`ls ~/.VirtualBox/*.vmdk | grep $device`
        if [[ -z "$checkstr1" && -z "$checkstr2" && -z "$checkstr3" ]]; then
          VBoxManage internalcommands createrawvmdk -filename ~/.VirtualBox/$device.vmdk -rawdisk /dev/$device -register
        fi
      fi
    done

    # Start VirtualBox
    VirtualBox

Note that your user has to be added to the "disk" group to create VMDKs out of existing drives.

### phpVirtualBox

An open source, AJAX implementation of the VirtualBox user interface written in PHP. As a modern web interface, it allows you to access and control remote VirtualBox instances. Much of its verbage and some of its code is based on the (inactive) vboxweb project. It allows the administrator to remotely, graphically, administer their virtual machines without having to log in to their headless VirtualBox servers.

This requires the PUEL edition for VirtualBox.

An installation guide is available here: http://code.google.com/p/phpvirtualbox/wiki/Installation

Arch Linux users should uncomment these 2 extensions in /etc/php/php.ini

    extension=json.so
    extension=soap.so

See also PhpVirtualBox

## 从其他虚拟机中迁移

`qemu-img` 程序可以用来将映像从一种格式转换到另一种格式，或为一个映像添加压缩或加密。

      # pacman -S qemu

### 从QEMU映像转换

To convert a QEMU image for use with VirtualBox, first convert it to raw format, then use VirtualBox's conversion utility to convert and compact it in its native format.

      $ qemu-img convert -O raw test.qcow2 test.raw
      $ VBoxManage modifyvdi /full/path/to/test.vdi compact
    or
      $ qemu-img convert -O raw test.qcow2 test.raw
        (of course you must have installed qemu package for that)
      $ VBoxManage convertfromraw /full/path/to/test.raw /full/path/to/test.vdi
      $ VBoxManage modifyvdi      /full/path/to/test.vdi compact

### 从VMware映像转换

运行

      $ VBoxManage clonehd source.vmdk target.vdi --format VDI

对于当前VirtualBox版本来说也许是不必要的（有待证实）

Categories:

- Emulators (简体中文)
- Virtualization (简体中文)