VirtualBox - Arch Linux 中文维基

跳至內容

# VirtualBox

出自 Arch Linux 中文维基
翻譯狀態：

- 本文（或部分內容）譯自 VirtualBox，最近一次同步於 2026-02-06，若英文版本有所更改，則您可以幫助同步與翻譯更改的內容。
- 您可以在 ArchWiki 的對應頁面找到本文翻譯的原始修訂歷史。
- 本文可能與英文原文存在出入。

相關文章

- /在虛擬機中安裝 Arch Linux
- Moving an existing install into (or out of) a virtual machine
- PhpVirtualBox
- RemoteBox

本文或本節需要翻譯。要貢獻翻譯，請訪問簡體中文翻譯團隊。

附註： 請提供模板的第一個位置參數以更詳細的指示。（在 Talk:VirtualBox# 中討論）

VirtualBox 是運行於現有作業系統之上的虛擬機監視器，用途是在特製環境（即虛擬機）裡運行作業系統。VirtualBox 處於活躍開發狀態，時常會引入新功能。VirtualBox 支持使用 Qt 圖形界面，以及在無界面模式下搭配 SDL 命令行工具運行和管理虛擬機。

為了實現某些主-客戶機間的整合功能，例如共享目錄與剪貼板、顯卡加速渲染、無縫窗口整合，VirtualBox 為部分作業系統提供了客戶機插件。

更多信息請參考 官方文檔。

## 在 Arch 裡安裝 VirtualBox

參考以下步驟在 Arch 主機系統中安裝 VirtualBox。

### 安裝基本軟體包

安裝 virtualbox包，並安裝以下內核模塊之一：

- 對於 linux包 內核，使用 virtualbox-host-modules-arch包
- 對於 linux-lts包 內核，使用 virtualbox-host-modules-lts包
- 對於其它內核，使用 virtualbox-host-dkms包

為了編譯 virtualbox-host-dkms包 提供的 VirtualBox 內核模塊，還需要安裝你使用的內核所對應的頭文件包（如 linux-rt包 需安裝 linux-rt-headers包）。[1] 當 VirtualBox 或內核更新的時候，DKMS 的 pacman 鉤子會自動重新編譯內核模塊。

### 模塊簽名

如果你的 Linux 內核是自行編譯的，並啟用了 `CONFIG_MODULE_SIG_FORCE` 選項，那麼你需要用編譯內核時所使用的密鑰為所有模塊簽名。

可以用根用戶（root）身份執行以下命令來為模塊進行簽名：

    # find "/lib/modules/$(uname -r)/" '(' -name 'vboxdrv.ko*' -o -name 'vboxnetadp.ko*' -o -name 'vboxnetflt.ko*' ')' -exec /lib/modules/$(uname -r)/build/scripts/sign-file sha256 /lib/modules/$(uname -r)/build/certs/signing_key.pem /lib/modules/$(uname -r)/build/certs/signing_key.x509 {} ';'

注意：哈希算法不必與配置時選擇的算法相匹配，但必須已被編譯進內核。

If you experience an error such as the following:

    At main.c:171:
    - SSL error:FFFFFFFF80000002:system library::No such file or directory: crypto/bio/bss_file.c:67
    - SSL error:10000080:BIO routines::no such file: crypto/bio/bss_file.c:75
    sign-file: certs/signing_key.pem

Then run the command `cd /lib/modules/$(uname -r)/build` to navigate to your kernel tree folder and check if the `certs` folder actually has a `signing_key.pem` file. If not, create a file somewhere on your system (does not have to be in the kernel tree folder) named `x509.genkey` with the following contents (based on Gentoo:Signed kernel module support#Building the kernel with proper keys):

    [ req ]
    default_bits = 4096
    distinguished_name = req_distinguished_name
    prompt = no
    string_mask = utf8only
    x509_extensions = myexts

    [ req_distinguished_name ]
    CN = Modules

    [ myexts ]
    basicConstraints=critical,CA:FALSE
    keyUsage=digitalSignature
    subjectKeyIdentifier=hash
    authorityKeyIdentifier=keyid

Then run `openssl req -new -nodes -utf8 -sha512 -days 36500 -batch -x509 -config x509.genkey -outform DER -out signing_key.x509 -keyout signing_key.pem` in the directory you created the `x509.genkey` file and move the resulting files to the `certs` directory in the kernel tree folder, then run `mokutil --import signing_key.x509` as root. You should then be able to rerun the signing command without an error.

If this still does not work, try updating your kernel to a newer version that has signing files already available (most kernel packages should), or if you are compiling your own, make sure that you copy the `src/(kernel version)/certs/signing_key.x509` and `src/(kernel version)/certs/signing_key.pem` from the folder you are building the kernel with to the `/lib/modules/$(uname -r)/build/certs` directory after you have built the kernel and are running it.

### 加載 VirtualBox 內核模塊

virtualbox-host-modules-arch包 和 virtualbox-host-dkms包 使用 `systemd-modules-load.service` 在啟動時自動加載 VirtualBox 的內核模塊。若要在安裝之後立即加載模塊，可以手動加載一次，或者乾脆重啟。可以從 `/usr/lib/modules-load.d/virtualbox-host-modules-arch.conf`，`/usr/lib/modules-load.d/virtualbox-host-modules-lts.conf` 或 `/usr/lib/modules-load.d/virtualbox-host-dkms.conf` 中查看加載的模塊列表。

注意：如果希望啟動時不自動加載 VirtualBox 模塊，需要將默認的 `/usr/lib/modules-load.d/virtualbox-host-modules-arch.conf`，`/usr/lib/modules-load.d/virtualbox-host-modules-lts.conf` 或 `/usr/lib/modules-load.d/virtualbox-host-dkms.conf` 配置文件屏蔽掉，具體做法是在 `/etc/modules-load.d/` 目錄裡創建同名的空文件，或是創建同名並連結到 `/dev/null` 的符號連結。

在 VirtualBox 所使用的內核模塊中，只有 `vboxdrv` 是必須的。該模塊必須在虛擬機運行之前加載。

手動加載模塊的命令是：

    # modprobe vboxdrv

以下模塊僅用於高級功能：

- `vboxnetadp` 和 `vboxnetflt`：這兩個模塊在使用橋接網絡或僅主機網絡功能時，都是需要的。具體來說，`vboxnetadp` 模塊用於在 VirtualBox 全局配置裡創建主機虛擬網卡；`vboxnetflt` 模塊會在啟動使用了該網卡的虛擬機時用到。

注意：如果在 VirtualBox 內核模塊運行期間你更新了模塊（所屬的軟體包），為了使用新版本，你需要手動重新加載這些模塊。在 root 權限下運行 `vboxreload` 即可重新加載。

### 從客機系統訪問主機 USB 設備

要讓虛擬機訪問主機的 USB 埠，需將允許使用該功能的用戶添加到 `vboxusers` 用戶組中。

### 客戶機插件

建議在運行 VirtualBox 的主機系統上安裝 virtualbox-guest-iso包 軟體包。這個包裡有個 `.iso` 鏡像文件，用來為 Arch 之外的客戶機系統安裝插件。鏡像文件的位置在 `/usr/lib/virtualbox/additions/VBoxGuestAdditions.iso`，手動在虛擬機的虛擬光碟機裡加載這個文件之後，即可在客戶機裡安裝插件。對於 Arch Linux 客戶機，請一併參考 /在虛擬機中安裝 Arch Linux#安裝客戶機插件

### 擴展包

Oracle VM VirtualBox Extension Pack 為虛擬機提供了額外功能。但它並不是以自由軟體協議發布的，僅供個人使用。這些擴展包可以從 virtualbox-ext-oracleAUR 安裝，也可以從 seblu 倉庫安裝編譯好的版本。

如果你喜歡使用傳統的手動方法來安裝擴展包，可以手動下載擴展包，然後通過 GUI 進行安裝（File > Tools > Extension Pack Manager），也可以在命令行中執行 `VBoxManage extpack install <.vbox-extpack>`。確保你有類似 Polkit 的工具來在安裝時為 VirtualBox 授予 root 權限。

You can also install the extension pack without using Polkit via the following command:

    # vboxmanage extpack install path-to-extension-pack

One of the non-free extension pack features is support for the Remote Desktop Protocol (RDP). This part of functionality can also be obtained with the open source VNC Extension Pack, by installing the virtualbox-ext-vnc包 package.

### 前端

VirtualBox 自帶四個前端：

- 如果你想通過常規 GUI 使用 VirtualBox，使用 `VirtualBox` 命令來啟動 VirtualBox。
- 如果你想在命令行下啟動與管理 VirtualBox，可以使用 `VBoxSDL` 命令。從 VBoxSDL 啟動的虛擬機，其窗口僅包含虛擬機的畫面，沒有菜單或是其他控制項。
- 如果你想在使用 VirtualBox 不使用任何 GUI（例如在伺服器上），使用 `VBoxHeadless` 命令。這時可以通過 VRDP 擴展來遠程訪問虛擬機的圖形界面。
- If you want to remotely manage virtual machines, the VirtualBox web service (`vboxwebsrv`) provides the server side backend. It can be used with RemoteBox (GUI) or phpVirtualBox (WebUI).

Refer to the VirtualBox manual to learn how to create virtual machines.

警告：If you intend to store virtual disk images on a Btrfs file system, before creating any images, you should consider disabling copy-on-write for the destination directory of these images.

A security feature in Wayland (i.e. when using GDM) disallows VirtualBox to grab all keyboard input. This is annoying when you want to pass window manager shortcuts to your guest operating system. It can be bypassed by whitelisting VirtualBox:

    $ gsettings get org.gnome.mutter.wayland xwayland-grab-access-rules
    $ gsettings set org.gnome.mutter.wayland xwayland-grab-access-rules "['VirtualBox Machine']"

The first command will show if any other applications are already whitelisted. If so, add VirtualBox Machine to that list, rather than having it as the only one.

## 在 VirtualBox 中安裝 Arch Linux

請參閱 /在虛擬機中安裝 Arch Linux。

## 虛擬磁碟管理

另請參閱 #Import/export VirtualBox virtual machines from/to other hypervisors。

### VirtualBox 支持的格式

VirtualBox 支持下列虛擬硬碟格式：

- VDI: Virtual Disk Image 格式是 VirtualBox 新建虛擬機時默認選用的格式，也是 VirtualBox 自有的開放容器格式。

- VMDK: Virtual Machine Disk 最初是由 VMware 為其產品研發的格式。該格式技術設計文檔最初是閉源的，而現在已經開源，在 VirtualBox 裡完全可用。這種格式有個功能是：把一個虛擬機的虛擬硬碟分割成多個 2GB 大小的文件。如果你要把虛擬機鏡像放在不支持大文件的文件系統（例如 FAT32）上，那麼這個功能就非常有用。在其它的虛擬磁碟格式裡，能做到同樣功能的只有 Parallels 的 HDD。

- VHD: Virtual Hard Disk 是 Microsoft 為 Windows Virtual PC 與 Hyper-V 研發的格式。如果你想把虛擬機部署到這些平台上，那麼你只能用這種格式。

  提示：Windows 7 開始可以直接掛載 VHD 文件進行讀寫，不需要額外安裝軟體。

- VHDX (只讀): 這是由 Microsoft 研發的 Virtual Hard Disk 格式的加強版。於 2012-09-04 與 Hyper-V 3.0 同步發布，二者都是 Windows Server 2012 的功能。該加強版的改進包括性能優化（源於區塊對齊），支持大區塊單位，還有應對斷電的磁碟日誌。VirtualBox 支持該格式的只讀訪問。

- HDD (V2): HDD 格式是由 Parallels Inc 研發的，由他們的虛擬機方案（如 Parallels Desktop for Mac）所使用。該格式的新版（v3 和 v4）由於缺少文檔，又是專有格式，未能被 VirtualBox 支持。
  注意：關於該格式「僅支持 V2 版」的說法目前有爭議。VirtualBox 官方手冊 聲稱只支持 V2 版，但 Wikipedia 上的說法是 V1 版也能正常工作。歡迎你對 V1 的支持狀況做測試驗證。

- QED: QEMU Enhanced Disk 是舊版 QEMU 使用的格式。QEMU 也是一個開源免費的虛擬機監視器。該格式設計於 2010 年，目的是要比 QCOW2 等格式更優秀。這種格式支持的功能包括全異步 I/O，數據高度完整性，文件備份及稀疏文件。VirtualBox 支持 QED 格式只是為了兼容由舊版 QEMU 創建的虛擬機。

- QCOW: QEMU Copy On Write 是 QEMU 現有版本支持的格式。QCOW 支持基於 zlib 實現的透明壓縮與加密（加密功能有缺陷，不推薦使用）。QCOW 包括兩個版本：QCOW 與 QCOW2。QCOW2 取代了舊版。VirtualBox 完全支持舊版 QCOW。QCOW2 包含兩個修訂版：QCOW2 0.10 和 QCOW2 1.1（QEMU 新建的虛擬機默認使用 1.1）。然而 VirtualBox 並不支持 QCOW2。

- OVF: Open Virtualization Format 是設計用於解決不同虛擬機監視器間的虛擬機互操作性和分發性的開放格式。VirtualBox 支持該格式的所有修訂版，具體的支持方式是 VBoxManage import/export 命令，但也有部分功能受限。

- RAW: 該模式下虛擬硬碟會直接暴露到物理硬碟上，不以任何容器格式進行封裝。VirtualBox 對此有多種支持方案：將 RAW 磁碟轉換成上述某種格式；將物理盤複製到 RAW 格式；直接掛載一個指向物理盤或 RAW 格式文件的 VMDK 文件。

### 轉換虛擬磁碟文件格式

VBoxManage clonehd 這個命令可以實現 VDI, VMDK, VHD 與 RAW 格式間的互轉：

    $ VBoxManage clonehd inputfile outputfile --format outputformat

以 VDI 轉成 VMDK 為例：

    $ VBoxManage clonehd source.vdi destination.vmdk --format VMDK

#### QCOW

VirtualBox 不支持 QEMU 的 QCOW2 格式。若要讓 VirtualBox 使用 QCOW2 格式的文件，你只能使用類似 qemu-img包 的工具將其轉換成已支持的格式。qemu-img 可以實現 QCOW 格式與 VDI, VMDK, VHDX, RAW 等其它格式間的互轉。具體支持的格式可以通過運行 `qemu-img --help` 命令查看。

該命令的一般形式是：

    $ qemu-img convert -O output_fmt inputfile outputfile

以 QCOW2 轉成 VDI 為例：

    $ qemu-img convert -O vdi source.qcow2 destination.vdi

提示：轉換時加上 `-p` 參數可以實時查看轉換進度

QCOW2 有兩個修訂版：0.10 和 1.1，用 `-o compat=revision` 參數可以指定具體版本。

### 在主機掛載虛擬硬碟

#### VDI

只能掛載固定大小的 VDI 鏡像（又名靜態鏡像），掛載動態鏡像較為困難。

首先要拿到 VDI 裡數據分區的偏移量 `offData`：

    $ VBoxManage internalcommands dumphdinfo storage.vdi | grep "offData"

然後再加上 `32256`（例如 69632 + 32256 = 101888），然後用這個命令來掛載：

    # mount -t ext4 -o rw,noatime,noexec,loop,offset=101888 storage.vdi /mntpoint/

For VDI disks with more partitions you can also use `losetup`:

    # losetup -o $offData -Pf

After this you should find the partitions under `/dev/loop*` (e.g. `/dev/loop0p1`). Then you can mount them as usual (e.g. `mount mount /dev/loop0p1 /mnt/`).

另一個辦法是用 mount.vdi 腳本來完成掛載。首先要把腳本安裝到 `/usr/bin/`，然後：

    # mount -t vdi -o fstype=ext4,rw,noatime,noexec vdi_file_location /mnt/

還可以使用 qemu-img包 提供的 nbd 內核模塊和 qemu-nbd 工具[2]：

    # modprobe nbd max_part=16
    # qemu-nbd -c /dev/nbd0 storage.vdi
    # mount /dev/nbd0p1 /mnt/dir/

需要卸載鏡像時執行：

    # umount /mnt/dir/
    # qemu-nbd -d /dev/nbd0

如果未能生成分區節點，試試運行命令：`partprobe /dev/nbd0`。另外，VDI 分區還可以直接用這個命令來映射到節點：`qemu-nbd -P 1 -c /dev/nbd0 storage.vdi`。

#### VHD

與 VDI 類似，可以使用 QEMU 的 nbd 模塊掛載 VHD 鏡像：

    # modprobe nbd
    # qemu-nbd -c /dev/nbd0 storage.vhd
    # mount /dev/nbd0p1 /mnt

需要卸載鏡像時執行：

    # umount /mnt
    # qemu-nbd -d /dev/nbd0

### 壓實虛擬硬碟

只有 .vdi 格式的虛擬磁碟文件可以壓實，具體操作步驟如下：

啟動虛擬機，手動刪除無用文件，或者使用類似 bleachbit包 的自動清理工具，該工具也有 Windows 版。

下一步要用零字節來填充可用空間。這有如下的可行方案：

- 如果你已經在用 Bleachbit 了，在 GUI 菜單裡選擇 System > Free disk space，或者在命令行執行：`bleachbit -c system.free_disk_space`；
- 在類 UNIX 系統裡，可以使用 `dd` 或 dcflddAUR（參閱這裡來了解兩者的區別）：

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

  當 `fillfile` 文件快占滿分區時，會出現這樣的錯誤信息：`1280 blocks (5120Mb) written.dcfldd:: No space left on device`。這意味著所有的可用空間與未保留區塊都已經被零字節填滿了。因為 ext 類系統會為 root 用戶默認保留一部分硬碟空間（見 `mkfs.ext4` 手冊頁對 `-m` 參數的解釋，或者用 `tune2fs -l` 命令來查看具體為 root 保留了多少空間），所以運行這一命令時需要有 root 權限。
  前面一步操作完成後，手動把 `fillfile` 刪掉。

- 在 Windows 系統裡有兩種辦法：
  - 由 Sysinternals Suite 提供的 `sdelete` 命令，用法是 `sdelete -s -z c:`。在虛擬機裡的每一個分區都要執行一遍（當然 c: 這個參數要對應地改成各個分區的盤符）；
  - 如果你喜歡腳本，可以用這個 PowerShell 實現的方案，但依然要每個分區執行一次：

        PS> ./Write-ZeroesToFreeSpace.ps1 -Root c:\ -PercentFree 0

    注意：該腳本需要在有管理員權限的 PowerShell 環境才能運行。默認的 PowerShell 配置下無法運行任何腳本，需要把執行策略至少調整到 `RemoteSigned`，而不能是 `Restricted`。用 `Get-ExecutionPolicy` 命令可以看到當前的執行策略，用 `Set-ExecutionPolicy RemoteSigned` 可以設置想要的執行策略。

完成這一步之後，將虛擬機關機。

下一次啟動虛擬機時，推薦先進行文件系統檢查：

- 在類 UNIX 系統上可以手動運行 `fsck` 來檢查；
  - 在 GNU/Linux 系統上（包括 Arch）可以通過內核啟動參數在系統啟動時強制執行硬碟檢查；
- 在 Windows 系統上：
  - 可以使用 `chkdsk c: /F`，其中 `c:` 可以替換成所有你希望檢查的盤符；
  - 或者從這裡下載 `FsckDskAll`。這和前面的 `chkdsk` 基本一樣，只是不必手動為每個分區執行一遍了。

接下來通過 VBoxManage modifyhd 移除 .vdi 文件中的零即可完成壓實過程：

    $ VBoxManage modifyhd your_disk.vdi --compact

注意：

- 如果你的虛擬機有保存過快照，那麼每個 .vdi 文件都要單獨執行一遍壓實操作。
- This concept of writing zeroes and compacting/reclaiming/cleanup space only works if there is no encryption on the virtual disk.
  - On Windows you can check whether BitLocker is enabled using the `manage-bde -status` command and disable it with `manage-bde -off c:`, where `c:` refers to the encrypted drive. After that, repeat the steps mentioned above.

#### TRIM

VirtualBox offers simulation of TRIM in VDI files via an experimental "discard" attachment option. This option is undocumented and can be accessed by commandline or .vbox file editing. When enabled, TRIM commands from the guest operating system causes the corresponding part of the VDI file to be compacted away.

警告：Using this option without Host I/O Cache is known to cause lockups.

### 擴充虛擬硬碟容量

#### 一般方法

如果你在創建虛擬機時給虛擬硬碟分配的容量太小了，VirtualBox 推薦的擴容方案是使用 VBoxManage modifyhd 這個命令。然而這個命令只支持 VDI 和 VHD 這兩種格式的動態分配容量版本。如果你想為固定大小的虛擬磁碟擴容，下面的辦法適用於 Windows 或類 UNIX 系統的虛擬機。

首先創建一個新的虛擬磁碟：

    $ VBoxManage createmedium disk -filename new.vdi --size 10000

`--size` 參數的值的單位是 MiB，在例子裡 10000 MiB ~= 10 GiB，new.vdi 是新創建的鏡像文件。

注意：該命令默認會創建標準（即動態分配）版本的文件格式，如果想創建固定大小的鏡像，需要追加參數 `--variant Fixed`。

接下來要把舊鏡像的內容複製到新鏡像裡去，這一步驟可能會花些時間：

    $ VBoxManage clonemedium disk old.vdi new.vdi --existing

卸載舊硬碟鏡像，掛載新鏡像，下面命令中的斜體字部分需要按照你的使用環境來換成真實的值：

    $ VBoxManage storageattach virtual_machine_name --storagectl SATA --port 0 --medium none
    $ VBoxManage storageattach virtual_machine_name --storagectl SATA --port 0 --medium new.vdi --type hdd

在上面的命令中，若要獲知存儲控制器的名字與埠號，可以使用命令：`VBoxManage showvminfo virtual_machine_name`。這會列印出如下的輸出（斜體標註的信息是有用的）：

    [...]
    Storage Controller Name (0):            IDE
    Storage Controller Type (0):            PIIX4
    Storage Controller Instance Number (0): 0
    Storage Controller Max Port Count (0):  2
    Storage Controller Port Count (0):      2
    Storage Controller Bootable (0):        on
    Storage Controller Name (1):            SATA
    Storage Controller Type (1):            IntelAhci
    Storage Controller Instance Number (1): 0
    Storage Controller Max Port Count (1):  30
    Storage Controller Port Count (1):      1
    Storage Controller Bootable (1):        on
    IDE (1, 0): Empty
    SATA (0, 0): /home/wget/IT/Virtual_machines/GNU_Linux_distributions/ArchLinux_x64_EFI/Snapshots/{6bb17af7-e8a2-4bbf-baac-fbba05ebd704}.vdi (UUID: 6bb17af7-e8a2-4bbf-baac-fbba05ebd704)
    [...]

下載 GParted Live 鏡像，在虛擬機裡將其掛載到虛擬光碟機中，啟動虛擬機，調整分區大小 / 位置，卸載鏡像並重啟。這樣擴容就完成了。

注意：如果虛擬盤使用了 GPT 分區表，擴容會導致 GPT 備份頭不再位於硬碟末尾。GParted 會詢問是否要將其修復，此時兩次詢問都要點 Fix。如果是 MBR 分區，就不存在這一問題。

最後，從 VirtualBox 裡註銷舊的鏡像文件，並把它刪掉：

    $ VBoxManage closemedium disk old.vdi
    $ rm old.vdi

#### 擴容 VDI 硬碟

如果你的虛擬硬碟是 VDI 格式的，請使用：

    $ VBoxManage modifymedium disk your_virtual_disk.vdi --resize the_new_size

然後回到上面的 Gparted 步驟，繼續完成擴容操作。

### 修改 .vbox 文件來替換虛擬硬碟

如果你覺得編輯 XML 文件比用 GUI 或 `VBoxManage` 更方便，那可以通過在虛擬機的 .vbox 配置文件中替換 GUID、文件路徑和格式來替換或添加虛擬硬碟：

    ArchLinux_vm.vbox

    <HardDisk uuid="{670157e5-8bd4-4f7b-8b96-9ee412a712b5}" location="ArchLinux_vm.vdi" format="VDI" type="Normal"/>

然後找到 `<StorageController>` 的子元素 `<AttachedDevice>`，把 GUID 屬性改成新鏡像文件的值：

    ArchLinux_vm.vbox

    <AttachedDevice type="HardDisk" port="0" device="0">
      <Image uuid="{670157e5-8bd4-4f7b-8b96-9ee412a712b5}"/>
    </AttachedDevice>

注意：如果你還不知道新鏡像文件的 GUID 值，可以用命令 `VBoxManage showhdinfo file` 來查看。如果你用 `VBoxManage clonehd` 命令來處理過虛擬盤，那麼在複製或轉換過程完成時，也會列印出 GUID 值。隨便寫一個 GUID 上去是不行的，必須與鏡像文件裡的 UUID 值相對應才行。

#### 在 Linux 宿主機和其它系統間遷移

.vbox 配置文件把虛擬盤和快照文件的位置記錄在 `<HardDisks> .... </HardDisks>` 標籤裡。如果新宿主系統存放虛擬機文件的路徑與舊宿主系統不同，你可以手動修改路徑值；如果 .vbox 文件與虛擬盤和快照文件夾位於相同目錄，也可以使用以下腳本，它會將修改後的新配置列印到標準輸出。

    #!/bin/sh
    NewPath="${PWD}/"
    Snapshots="Snapshots/"
    Filename="$1"

     awk -v SetPath="$NewPath" -v SnapPath="$Snapshots" '{if(index($0,"<HardDisk uuid=") != 0){A=$3;split(A,B,"=");
    L=B[2];
     gsub(/\"/,"",L);
      sub(/^.*\//,"",L);
      sub(/^.*\\/,"",L);
     if(index($3,"{") != 0){SnapS=SnapPath}else{SnapS=""};
      print $1" "$2" location="\"SetPath SnapS L"\" "$4" "$5}
    else print $0}' "$Filename"

注意：

- 如果你想把虛擬機遷移到 Windows 宿主系統上去，文件路徑裡應該使用 `\` 而不是 `/`。
- 這個腳本判斷快照的邏輯是：文件名是否包含 `{`。
- 為了在新宿主機上運行起來，首先得在管理界面註冊：點選菜單項 Machine -> Add... 或者按快捷鍵 `Ctrl+a` ，然後找到 .vbox 配置文件。也可以用命令行：`VBoxManage registervm filename.vbox`

### 複製虛擬盤並為其分配新 UUID

VirtualBox 廣泛應用了 UUID。每個虛擬機和虛擬機的各個虛擬盤必須有不同的 UUID，在啟動虛擬機時，VirtualBox 會跟蹤虛擬機實例的所有 UUID。用 VBoxManage list 命令可以列出 VirtualBox 管理的所有資源。

如果你想複製一台虛擬機，僅複製虛擬盤鏡像文件是不夠的。你還得給複製出的新鏡像文件分配一個新的 UUID。否則在同一個 VirtualBox 的環境裡無法同時註冊兩個具有相同 UUID 的鏡像文件。

下面這個命令可以用來為虛擬盤分配新 UUID：

    $ VBoxManage internalcommands sethduuid /path/to/disk.vdi

提示：用 VBoxManage clonehd 可以一次性完成複製內容與分配新 UUID
注意：上述命令可以用於任意 VirtualBox 所支持的鏡像格式。

## 使用技巧

### Import/export VirtualBox virtual machines from/to other hypervisors

If you plan to use your virtual machine on another hypervisor or want to import in VirtualBox a virtual machine created with another hypervisor, you might be interested in reading the following steps.

#### Remove additions

Guest additions are available in most hypervisor solutions: VirtualBox comes with the Guest Additions, VMware with the VMware Tools, Parallels with the Parallels Tools, etc. These additional components are designed to be installed inside a virtual machine after the guest operating system has been installed. They consist of device drivers and system applications that optimize the guest operating system for better performance and usability by providing these features.

If you have installed the additions to your virtual machine, please uninstall them first. Your guest, especially if it is using an operating system from the Windows family, might behave weirdly, crash or even might not boot at all if you are still using the specific drivers in another hypervisor.

#### Use the right virtual disk format

This step will depend on the ability to convert the virtual disk image directly or not.

##### Automatic tools

Some companies provide tools which offer the ability to create virtual machines from a Windows or GNU/Linux operating system located either in a virtual machine or even in a native installation. With such a product, you do not need to apply this and the following steps and can stop reading here.

- Parallels Transporter which is non free, is a product from Parallels Inc. This solution basically consists in an piece of software called agent that will be installed in the guest you want to import/convert. Then, Parallels Transporter, which only works on OS X, will create a virtual machine from that agent which is contacted either by USB or Ethernet network.
- VMware vCenter Converter[失效連結 2024-07-30 ⓘ] which is free upon registration on the VMware website, works nearly the same way as Parallels Transporter, but the piece of software that will gather the data to create the virtual machine only works on a Windows platform.

##### Manual conversion

First, familiarize yourself with the formats supported by VirtualBox and those supported by third-party hypervisors.

- Importing or exporting a virtual machine from/to a VMware solution is not a problem at all if you use the VMDK or OVF disk format, otherwise converting VMDK to VDI and VDI to VMDK is possible and the aforementioned VMware vCenter Converter tool is available.
- Importing or exporting from/to QEMU is not a problem neither: some QEMU formats are supported directly by VirtualBox and conversion between QCOW2 to VDI and VDI to QCOW2 is still available if needed.
- Importing or exporting from/to Parallels hypervisor is the hardest way: Parallels does only support its own HDD format (even the standard and portable OVF format is not supported!).

  - To export your virtual machine to Parallels, you will need to use the Parallels Transporter tool described above.
  - To import your virtual machine to VirtualBox, you will need to use the VMware vCenter Converter described above to convert the virtual machine to the VMware format first. Then, apply the solution to migrate from VMware.

#### Create the virtual machine configuration for your hypervisor

Each hypervisor have their own virtual machine configuration file: .vbox for VirtualBox, .vmx for VMware, a `config.pvs` file located in the virtual machine bundle (.pvm file), etc. You will have thus to recreate a new virtual machine in your new destination hypervisor and specify its hardware configuration as close as possible as your initial virtual machine.

Pay a close attention to the firmware interface (BIOS or UEFI) used to install the guest operating system. While an option is available to choose between these 2 interfaces on VirtualBox and on Parallels solutions, on VMware, you will have to add manually the following line to your .vmx file.

    ArchLinux_vm.vmx

    firmware = "efi"

Finally, ask your hypervisor to use the existing virtual disk you have converted and launch the virtual machine.

提示：

- On VirtualBox, if you do not want to browse the whole GUI to find the right location to add your new virtual drive device, you can Replace a virtual disk manually from the .vbox file, or use the `VBoxManage storageattach` described in #Increasing the size of VDI disks or in the VirtualBox manual page.
- Similarly, in VMware products, you can replace the location of the current virtual disk location by adapting the .vmdk file location in your .vmx configuration file.

### Virtual machine launch management

#### Starting virtual machines with a service (autostart)

Find hereafter the implementation details of a systemd service that will be used to consider a virtual machine as a service.

    /etc/systemd/system/vboxvmservice@.service

    [Unit]
    Description=VBox Virtual Machine %i Service
    Requires=systemd-modules-load.service
    After=systemd-modules-load.service

    [Service]
    User=username
    Group=vboxusers
    ExecStart=/usr/bin/VBoxManage startvm %i --type startmode
    ExecStop=/usr/bin/VBoxManage controlvm %i stopmode
    RemainAfterExit=yes

    [Install]
    WantedBy=multi-user.target

注意：

- Replace `username` with a user that is a member of the `vboxusers` group. Make sure the user chosen is the same user that will create/import virtual machines, otherwise the user will not see the virtual machine appliances.
- Replace `startmode` with a virtual machine frontend type, usually `gui`, `headless` or `separate`
- Replace `stopmode` with desired state switch, usually `savestate` or `acpipowerbutton`
- If you have multiple virtual machines managed by systemd and they are not stopping properly, try to add `KillMode=none` and `TimeoutStopSec=40` at the end of `[Service]` section.

Enable the `vboxvmservice@your_virtual_machine_name` systemd unit in order to launch the virtual machine at next boot. To launch it directly, simply start the systemd unit.

VirtualBox 4.2 introduces a new way for UNIX-like systems to have virtual machines started automatically, other than using a systemd service.

#### Starting virtual machines with a keyboard shortcut

It can be useful to start virtual machines directly with a keyboard shortcut instead of using the VirtualBox interface (GUI or CLI). For that, you can simply define key bindings in `.xbindkeysrc`. Please refer to Xbindkeys for more details.

Example, using the `Fn` key of a laptop with an unused battery key (`F3` on the computer used in this example):

    "VBoxManage startvm 'Windows 7'"
    m:0x0 + c:244
    XF86Battery

注意：If you have a space in the name of your virtual machine, then enclose it with single apostrophes like made in the example just above.

### Use specific device in the virtual machine

#### Using USB webcam / microphone

注意：You will need to have extension pack installed before following the steps below.

1. Make sure the virtual machine is not running and your webcam / microphone is not being used.
2. Bring up the main VirtualBox window and go to settings for Arch machine. Go to USB section.
3. Make sure Enable USB Controller is selected. Also make sure that Enable USB 2.0 (EHCI) Controller is selected too.
4. Click the Add filter from device button (the cable with the + icon).
5. Select your USB webcam/microphone device from the list.
6. Now click OK and start your virtual machine.

注意：If your Microphone does not show up in the "Add filter from device" menu, try the USB 3.0 and 1.1 options instead (In Step 3).

#### Detecting web-cams and other USB devices

注意：This will not do much if you are running a Linux/Unix operating system inside of your virtual machine, as most do not have autodetection features.

If the device that you are looking for does not show up on any of the menus in the section above and you have tried all three USB controller options, boot up your virtual machine three separate times. Once using the USB 1.1 controller, another using the USB 2.0 controller, etc. Leave the virtual machine running for at least 5 minutes after startup. Sometimes Windows will autodetect the device for you. Be sure you filter any devices that are not a keyboard or a mouse so they do not start up at boot. This ensures that Windows will detect the device at start-up.

### Access a guest server

To access Apache server on a Virtual Machine 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 virtual machine 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 that host machine. This can also be set up to work with SSH or any other services by changing "Apache" to the corresponding service and ports.

注意：`pcnet` refers to the network card of the virtual machine. If you use an Intel card in your virtual machine settings, change `pcnet` to `e1000`.

To communicate between the VirtualBox guest and host using ssh, the server port must be forwarded under Settings > Network. When connecting from the client/host, connect to the IP address of the client/host machine, as opposed to the connection of the other machine. This is because the connection will be made over a virtual adapter.

### D3D acceleration in Windows guests

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. These libraries are now part of VirtualBox guest additions.

After enabling OpenGL acceleration as described above, reboot the guest into safe mode (press F8 before the Windows screen appears but after the VirtualBox screen disappears), and install VirtualBox guest additions, during install enable checkbox Direct3D support. Reboot back to normal mode and you should have accelerated Direct3D.

注意：

- This hack may or may not work for some games depending on what hardware checks they make and what parts of D3D they use.
- This was tested on Windows XP, 7 and 8.1. If method does not work on your Windows version please add data here.

### VirtualBox on a USB key

When using VirtualBox on a USB key, for example to start an installed machine with an ISO image, you will manually have to create VMKDs 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:

本文或本章節的語言、語法或風格需要改進。參考：幫助:風格

原因：The following script parses the output of ls, which is very brittle and known to break.（在Talk:VirtualBox討論）

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

### Run a native Arch Linux installation inside VirtualBox

If you have a dual boot system between Arch Linux and another operating system, it can become tedious to switch back and forth if you need to work in both. You may also experience performance or compatibility issues when using a virtual machine, which can impact your ability to do certain tasks.

This guide will let you reuse, in a virtual machine, your native Arch Linux installation when you are running your second operating system. This way, you keep the ability to run each operating system natively, but have the option to run your Arch Linux installation inside a virtual machine.

#### Make sure you have a persistent naming scheme

Depending on your hard drive setup, device files representing your hard drives may appear differently when you will run your Arch Linux installation natively or in virtual machine. This problem occurs when using FakeRAID for example. The fake RAID device will be mapped in `/dev/mapper/` when you run your GNU/Linux distribution natively, while the devices are still accessible separately. However, in your virtual machine, it can appear without any mapping in `/dev/sdaX` for example, because the drivers controlling the fake RAID in your host operating system (e.g. Windows) are abstracting the fake RAID device.

To circumvent this problem, we will need to use an addressing scheme that is persistent to both systems. This can be achieved using UUIDs. Make sure your boot loader and fstab file is using UUIDs, otherwise fix this issue. Read fstab and Persistent block device naming.

警告：

- Make sure your host partition is only accessible in read only from your Arch Linux virtual machine, this will avoid risk of corruptions if you were to corrupt that host partition by writing on it due to lack of attention.
- You should NEVER allow VirtualBox to boot from the entry of your second operating system, which, as a reminder, is used as the host for this virtual machine! Take thus a special care especially if your default boot loader/boot manager entry is your other operating system. Give a more important timeout or put it below in the order of preferences.

#### Make sure your mkinitcpio image is correct

Make sure your mkinitcpio configuration uses the HOOK `block`:

    /etc/mkinitcpio.conf

    ...
    HOOKS=(base udev autodetect microcode modconf kms keyboard keymap consolefont block filesystems fsck)
    ...

If it is not present, add it and regenerate the initramfs.

#### Create a virtual machine configuration to boot from the physical drive

##### Create a raw disk VMDK image

Now, we need to create a new virtual machine which will use a RAW disk as virtual drive, for that we will use a ~ 1Kio VMDK file which will be mapped to a physical disk. Unfortunately, VirtualBox does not have this option in the GUI, so we will have to use the console and use an internal command of `VBoxManage`.

Boot the host which will use the Arch Linux virtual machine. The command will need to be adapted according to the host you have.

On a GNU/Linux host

There are 3 ways to achieve this: login as root, changing the access right of the device with `chmod`, adding your user to the `disk` group. The latter way is the more elegant, let us proceed that way:

    # gpasswd -a your_user disk

Apply the new group settings with:

    $ newgrp

Now, you can use the command:

    $ VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sdb -register

Adapt the above command to your need, especially the path and filename of the VMDK location and the raw disk location to map which contain your Arch Linux installation.

On a Windows host

Open a command prompt must be run as administrator.

提示：On Windows, open your start menu/start screen, type `cmd`, and type `Ctrl+Shift+Enter`, this is a shortcut to execute the selected program with admin rights.

On Windows, as the disk filename convention is different from UNIX, use this command to determine what drives you have in your Windows system and their location:

    # wmic diskdrive get name,size,model

    Model                               Name                Size
    WDC WD40EZRX-00SPEB0 ATA Device     \\.\PHYSICALDRIVE1  4000783933440
    KINGSTON SVP100S296G ATA Device     \\.\PHYSICALDRIVE0  96024821760
    Hitachi HDT721010SLA360 ATA Device  \\.\PHYSICALDRIVE2  1000202273280
    Innostor Ext. HDD USB Device        \\.\PHYSICALDRIVE3  1000202273280

In this example, as the Windows convention is `\\.\PhysicalDriveX` where X is a number from 0, `\\.\PHYSICALDRIVE1` could be analogous to `/dev/sdb` from the Linux disk terminology.

To use the `VBoxManage` command on Windows, you can either, change the current directory to your VirtualBox installation folder first with `cd C:\Program Files\Oracle\VirtualBox\`

    # .\VBoxManage.exe internalcommands createrawvmdk -filename C:\file.vmdk -rawdisk \\.\PHYSICALDRIVE1

or use the absolute path name:

    # "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" internalcommands createrawvmdk -filename C:\file.vmdk -rawdisk \\.\PHYSICALDRIVE1

On another operating system host

There are other limitations regarding the aforementioned command when used in other operating systems like OS X, please thus read carefully the manual page, if you are concerned.

##### Create the virtual machine configuration file

注意：

- To make use of the VBoxManage command on Windows, you need to change the current directory to your VirtualBox installation folder first: `cd C:\Program Files\Oracle\VirtualBox\`.
- Windows makes use of backslashes instead of slashes, please replace all slashes `/` occurrences by backslashes `\` in the commands that follow when you will use them.

After, we need to create a new machine (replace the virtual_machine_name to your convenience) and register it with VirtualBox.

    $ VBoxManage createvm -name virtual_machine_name -register

Then, the newly raw disk needs to be attached to the machine. This will depend if your computer or actually the root of your native Arch Linux installation is on an IDE or a SATA controller.

If you need an IDE controller:

    $ VBoxManage storagectl virtual_machine_name --name "IDE Controller" --add ide
    $ VBoxManage storageattach virtual_machine_name --storagectl "IDE Controller" --port 0 --device 0 --type hdd --medium /path/to/file.vmdk

otherwise:

    $ VBoxManage storagectl virtual_machine_name --name "SATA Controller" --add sata
    $ VBoxManage storageattach virtual_machine_name --storagectl "SATA Controller" --port 0 --device 0 --type hdd --medium /path/to/file.vmdk

While you continue using the CLI, it is recommended to use the VirtualBox GUI, to personalise the virtual machine configuration. Indeed, you must specify its hardware configuration as close as possible as your native machine: turning on the 3D acceleration, increasing video memory, setting the network interface, etc.

Finally, you may want to seamlessly integrate your Arch Linux with your host operating system and allow copy pasting between both operating systems. Please refer to VirtualBox/Install Arch Linux as a guest#Install the Guest Additions for that, since this Arch Linux virtual machine is basically an Arch Linux guest.

警告：For Xorg to work in natively and in the virtual machine, since obviously it will be using different drivers, it is best if there is no `/etc/X11/xorg.conf`, so Xorg will pick up everything it needs on the fly. However, if you really do need your own Xorg configuration, maybe is it worth to set your default systemd target to `multi-user.target` with `systemctl isolate graphical.target` as root (more details at systemd#Targets and systemd#Change current target). In that way, the graphical interface is disabled (i.e. Xorg is not launched) and after you logged in, you can `startx`} manually with a custom `xorg.conf`.

### Install a native Arch Linux system from VirtualBox

In some cases it may be useful to install a native Arch Linux system while running another operating system: one way to accomplish this is to perform the installation through VirtualBox on a raw disk. If the existing operating system is Linux based, you may want to consider following Install from existing Linux instead.

This scenario is very similar to #Run a native Arch Linux installation inside VirtualBox, but will follow those steps in a different order: start by #Create a raw disk VMDK image, then #Create the virtual machine configuration file.

Now, you should have a working virtual machine configuration whose virtual VMDK disk is tied to a real disk. The installation process is exactly the same as the steps described in VirtualBox/Install Arch Linux as a guest, but #Make sure you have a persistent naming scheme and #Make sure your mkinitcpio image is correct.

警告：

- For BIOS systems and MBR disks, do not install a boot loader inside your virtual machine, this will not work since the MBR is not linked to the MBR of your real machine and your virtual disk is only mapped to a real partition without the MBR.
- For UEFI systems without CSM and GPT disks, the installation will not work at all since:
  - the EFI system partition is not mapped to your virtual disk and Arch Linux requires to have the Linux kernel on it to boot as an EFI application (see EFI boot stub for details);
  - and the efivars, if you are installing Arch Linux using the EFI mode brought by VirtualBox, are not the one of your real system: the bootmanager entries will hence not be registered.
- This is why, it is recommended to create your partitions in a native installation first, otherwize the partitions will not be taken into consideration in your MBR/GPT partition table.

After completing the installation, boot your computer natively with an GNU/Linux installation media (whether it be Arch Linux or not), chroot into your installed Arch Linux installation and install and configure a boot loader.

### Install MacOS guest

Before starting the virtual machine, run the following commands on the host machine [3]:

    $ VBoxManage modifyvm "MyMacVM" --cpuid-set 00000001 000106e5 00100800 0098e3fd bfebfbff
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/efi/0/Config/DmiSystemProduct" "iMac11,3"
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/efi/0/Config/DmiSystemVersion" "1.0"
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct" "Iloveapple"
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/smc/0/Config/DeviceKey" "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC" 1
    $ VBoxManage setextradata "MyMacVM" VBoxInternal2/EfiGopMode 4

If you use an AMD processor and the first boot gets stuck, you also have to run

    $ VBoxManage modifyvm "MyMacVM" --cpu-profile "Intel Core i7-6700K"

#### No keyboard/mouse input when attempting to install Mojave

If you are attempting to install Mojave, after doing the aforementioned steps, the installer will load up but you might not be able to send keyboard or mouse input. The reason seems to be that Mojave no longer supports the USB 1.1 controllers and in order to fix the issue you need to emulating USB 3.0. To do that first install the extension pack.

Then go to Machine > Settings > USB and select USB 3.0. Input should work from this point onwards.

#### UEFI interactive shell after restart

If the installer is unable to properly format the bootable drive during installation and you end up in an UEFI shell, enter the following:

1. Type `exit` at the UEFI prompt
2. Select Boot Maintenance Manager
3. Select Boot From File

You will now be brought to couple of obscure PCI paths. The first one is the one that you just attempted to boot from and it did not work. The second (or third) one should be the one with the MacOS recovery partition that you need to load to continue the installation. Click the second Entry. If it is empty, press `Esc` to go back and select the third entry. Once you get one with folders click though the folders. It should be something like macOS Install Data > Locked Files > Boot Files > boot.efi. Once you click enter on the boot.efi you should boot into the MacOS installer and resume installation. Note that some of the subdirectories might be missing. Remember that you need to get to a `boot.efi`.[4]

### Move a native Windows installation to a virtual machine

If you want to migrate an existing native Windows installation to a virtual machine which will be used with VirtualBox on GNU/Linux, this use case is for you. This section only covers native Windows installation using the MSDOS/Intel partition scheme. Your Windows installation must reside on the first MBR partition for this operation to success. Operation for other partitions are available but have been untested (see #Known limitations for details).

警告：If you are using an OEM version of Windows, this process is unauthorized by the end user license license. Indeed, the OEM license typically states the Windows install is tied with the hardware together. Transferring a Windows install to a virtual machine removes this link. Make thus sure you have a full Windows install or a volume license model before continuing. If you have a full Windows license but the latter is not coming in volume, nor as a special license for several PCs, this means you will have to remove the native installation after the transfer operation has been achieved.

A couple of tasks are required to be done inside your native Windows installation first, then on your GNU/Linux host.

#### Tasks on Windows

The first three following points comes from this outdated VirtualBox wiki page, but are updated here.

- Remove IDE/ATA controllers checks (Windows XP only): Windows memorize the IDE/ATA drive controllers it has been installed on and will not boot if it detects these have changed. The solution proposed by Microsoft is to reuse the same controller or use one of the same serial, which is impossible to achieve since we are using a Virtual Machine. MergeIDE, a German tool, developped upon another other solution proposed by Microsoft can be used. That solution basically consists in taking all IDE/ATA controller drivers supported by Windows XP from the initial driver archive (the location is hard coded, or specify it as the first argument to the .bat script), installing them and registering them with the regedit database.
- Use the right type of Hardware Abstraction Layer (old 32 bits Windows versions): Microsoft ships 3 default versions: `Hal.dll` (Standard PC), `Halacpi.dll` (ACPI HAL) and `Halaacpi.dll` (ACPI HAL with IO APIC). Your Windows install could come installed with the first or the second version. In that way, please disable the Enable IO/APIC VirtualBox extended feature.
- Disable any AGP device driver (only outdated Windows versions): If you have the files `agp440.sys` or `intelppm.sys` inside the `C:\Windows\SYSTEM32\drivers\` directory, remove it. As VirtualBox uses a PCI virtual graphics card, this can cause problems when this AGP driver is used.
- Create a Windows recovery disk: In the following steps, if things turn bad, you will need to repair your Windows installation. Make sure you have an install media at hand, or create one with Create a recovery disk from Vista SP1, Create a system repair disc on Windows 7 or Create a recovery drive on Windows 8.x).

#### Using Disk2vhd to clone Windows partition

Boot into Windows, clean up the installation (with CCleaner for example), use disk2vhd tool to create a VHD image. Include a reserved system partition (if present) and the actual Windows partition (usually disk C:). The size of Disk2vhd-created image will be the sum of the actual files on the partition (used space), not the size of a whole partition. If all goes well, the image should just boot in a virtual machine and you will not have to go through the hassle with MBR and Windows boot loader, as in the case of cloning an entire partition.

#### Tasks on GNU/Linux

提示：Skip the partition-related parts if you created VHD image with Disk2vhd.

- Reduce the native Windows partition size to the size Windows actually needs with `ntfsresize` available from ntfs-3g包. The size you will specify will be the same size of the VDI that will be created in the next step. If this size is too low, you may break your Windows install and the latter might not boot at all.

  Use the `--no-action` option first to run a test:

      # ntfsresize --no-action --size 52Gi /dev/sda1

  If only the previous test succeeded, execute this command again, but this time without the aforementioned test flag.

- Install VirtualBox on your GNU/Linux host (see #Installation steps for Arch Linux hosts if your host is Arch Linux).

- Create the Windows disk image from the beginning of the drive to the end of the first partition where is located your Windows installation. Copying from the beginning of the disk is necessary because the MBR space at the beginning of the drive needs to be on the virtual drive along with the Windows partition. In this example two following partitions `sda2` and `sda3`will be later removed from the partition table and the MBR boot loader will be updated.

      # sectnum=$(( $(cat /sys/block/sda/sda1/start) + $(cat /sys/block/sda/sda1/size) ))

  Using `cat /sys/block/sda/sda1/size` will output the number of total sectors of the first partition of the disk `sda`. Adapt where necessary.

      # dd if=/dev/sda bs=512 count=$sectnum | VBoxManage convertfromraw stdin windows.vdi $(( $sectnum * 512 ))

  We need to display the size in byte, `$(( $sectnum * 512 ))` will convert the sector numbers to bytes.

- Since you created your disk image as root, set the right ownership to the virtual disk image:

      # chown your_user:your_group windows.vdi

- Create your virtual machine configuration file and use the virtual disk created previously as the main virtual hard disk.

- Try to boot your Windows virtual machine, it may just work. First though remove and repair disks from the boot process as it may interfere (and likely will) booting into safe-mode.

- Attempt to boot your Windows virtual machine in safe mode (press the F8 key before the Windows logo shows up)... if running into boot issues, read #Fix MBR and Microsoft boot loader. In safe-mode, drivers will be installed likely by the Windows plug-and-play detection mechanism view. Additionally, install the VirtualBox Guest Additions via the menu Devices > Insert Guest Additions CD image.... If a new disk dialog does not appear, navigate to the CD drive and start the installer manually.

- You should finally have a working Windows virtual machine. Do not forget to read the #Known limitations.

- Performance tip: according to VirtualBox manual, SATA controller has a better performance than IDE. If you cannot boot Windows off virtual SATA controller right away, it is probably due to the lack of SATA drivers. Attach virtual disk to IDE controller, create an empty SATA controller and boot the virtual machine - Windows should automatically install SATA drivers for the controller. You can then shutdown the virtual machine, detach virtual disk from IDE controller and attach it to SATA controller instead.

#### Fix MBR and Microsoft boot loader

If your Windows virtual machine refuses to boot, you may need to apply the following modifications to your virtual machine.

- Boot a GNU/Live live distribution inside your virtual machine before Windows starts up.

- Remove other partitions entries from the virtual disk MBR. Indeed, since we copied the MBR and only the Windows partition, the entries of the other partitions are still present in the MBR, but the partitions are not available anymore. Use `fdisk` to achieve this for example.

      fdisk ''/dev/sda''
      Command (m for help): a
      Partition number (''1-3'', default ''3''): ''1''

- Write the updated partition table to the disk (this will recreate the MBR) using the `m` command inside `fdisk`.

- Use testdisk包 (see here for details) to add a generic MBR:

      # testdisk > Disk /dev/sda... > [Proceed] > [Intel] Intel/PC partition > [MBR Code] Write TestDisk MBR to first sector > Write a new copy of MBR code to first sector? (Y/n) > Y > Write a new copy of MBR code, confirm? (Y/N) > A new copy of MBR code has been written. You have to reboot for the change to take effect. > [OK]

- With the new MBR and updated partition table, your Windows virtual machine should be able to boot. If you are still encountering issues, boot your Windows recovery disk from on of the previous step, and inside your Windows RE environment, execute the commands described here.

#### Known limitations

- Your virtual machine can sometimes hang and overrun your RAM, this can be caused by conflicting drivers still installed inside your Windows virtual machine. Good luck to find them!
- Additional software expecting a given driver beneath may either not be disabled/uninstalled or needs to be uninstalled first as the drivers that are no longer available.
- Your Windows installation must reside on the first partition for the above process to work. If this requirement is not met, the process might be achieved too, but this had not been tested. This will require either copying the MBR and editing in hexadecimal see VirtualBox: booting cloned disk or will require to fix the partition table manually or by repairing Windows with the recovery disk you created in a previous step. Let us consider our Windows installation on the second partition; we will copy the MBR, then the second partition where to the disk image. `VBoxManage convertfromraw` needs the total number of bytes that will be written: calculated thanks to the size of the MBR (the start of the first partition) plus the size of the second (Windows) partition. `{ dd if=/dev/sda bs=512 count=$(cat /sys/block/sda/sda1/start) ; dd if=/dev/sda2 bs=512 count=$(cat /sys/block/sda/sda2/size) ; } | VBoxManage convertfromraw stdin windows.vdi $(( ($(cat /sys/block/sda/sda1/start) + $(cat /sys/block/sda/sda2/size)) * 512 ))`.

### Run a native Windows installation inside VirtualBox

注意：The technique outlined in this section only applies to UEFI systems.

In some cases, it is useful to be able to dual boot with Windows and access the partition in a virtual machine. This process is significantly different from #Move a native Windows installation to a virtual machine in several ways:

- The Windows partition is not copied to a virtual disk image. Instead, a raw VMDK file is created;
- Changes in the virtual machine will be mirrored in the partition, and vice versa;
- OEM licenses should still be satisfied, since the Windows partition still boots directly on the hardware.

警告：Some of the commands used here can corrupt either the Windows partition, the Arch Linux partition, or both. Use extreme caution when executing commands, and double check that they are being run in the correct shell. It would be a good idea to have a backup of the entire drive ready before beginning this process.
注意：Before proceeding be sure to have access to a Windows installation media (such as the Windows 11 ISO).

#### Creating the virtual machine

A VirtualBox virtual machine must be manually created. As of now do not add any storage device any disk to the virtual machine, it will be done manually later.

Configure the virtual machine with the following settings (settings panel can be opened by clicking the "Settings" button in the main toolbar):

- View: System:
  - Tab: Motherboard:
    - mark Enable I/O APIC;
    - mark Enable EFI;
    - mark Hardware Clock in UTC Time if is your case.
  - Tab: Processor:
    - mark Enable PAE/NX;
    - mark Enable Nested VT-x/AMD-V;
  - Tab: Acceleration:
    - Choose the paravirtualization interface Hyper-V from the drop down menu;
    - mark Enable Nested Paging.

Optionally you can enable also the following settings:

- View: Display
  - Tab: Screen
    - mark Enable 3D Acceleration. Note that it could cause glitches.

注意：The Hyper-V setting is not required in order for the system to operate correctly, but it may help avoid licensing issues.

#### Creating virtual machine disks

To access the Windows partitions, create a raw VMDK file pointing to the relevant Windows partitions (root privileges are required to read disk partition table):

    # VBoxManage createmedium disk -filename VM_DIRECTORY/windows.vmdk --format=VMDK --variant RawDisk --property RawDrive=DISK --property Partitions=RESERVED_PARTITION_NUMBER,BASIC_DATA_PARTITION_NUMBER

Replace capitalized placeholder strings as follow:

- `VM_DIRECTORY` with the path of the virtual machine folder (usually a subdirectory of `~/VirtualBox VMs`;
- `DISK` must be replaced with the block device containing all the Windows partitions (e.g.: `/dev/sda` or `/dev/nvme0n1`);
- `RESERVED_PARTITION_NUMBER` must be replaced with the number of partition labeled "Microsoft reserved partition" (e.g.: if the partition is the `/dev/sda2` the number will be `2`);
- `BASIC_DATA_PARTITION_NUMBER` must be replaced with the partition containing the Windows installation (e.g.: if the partition is the `/dev/sda3` the number will be `3`);

Example:

    # VBoxManage createmedium disk -filename "/home/user/VirtualBox VMs/windows.vmdk" --format=VMDK --variant RawDisk --property RawDrive=/dev/nvme0n1 --property Partitions=2,3

The command will also create an extra file inside the virtual machine folder, "windows-pt.vmdk", that will be just ignored.

注意：`windows.vmdk` must be re-created if the partition table is changed.
提示：

Partition numbers can be found also by running this command and looking at the MIN column:

    lsblk --output NAME,PARTLABEL,FSTYPE,MAJ:MIN,SIZE

    NAME        PARTLABEL                    FSTYPE UUID                                 MAJ:MIN   SIZE
    nvme0n1                                                                              259:0   931,5G
    ├─nvme0n1p1 EFI system partition         vfat   90DC-A6B3                            259:1     100M
    ├─nvme0n1p2 Microsoft reserved partition                                             259:2      16M
    ├─nvme0n1p3 Basic data partition         ntfs   D2A2A104A2A0EE63                     259:3     200G
    ...

Now change the virtual disk owner to give access the user and group running VirtualBox.

    # chown VIRTUALBOX_RUNNING_USER:VIRTUALBOX_RUNNING_GROUP VM_DIRECTORY/windows.vmdk VM_DIRECTORY/windows-pt.vmdk

Replace `VIRTUALBOX_RUNNING_USER` and `VIRTUALBOX_RUNNING_GROUP` with the user and the group that will run VirtualBox, which most likely will be your user.

#### Allowing VirtualBox to read physical partitions

VirtualBox must have raw disk access in order to run a Windows partition. Normally, this would require VirtualBox to be run with full root privileges, but more elegant options are available.

##### Higher security option: using a dedicated group for the Windows partitions

Here udev is configured to restrict the access to partitions Windows partitions to the vboxusers group, and then the user running VirtualBox is added to the group.

Assigning the disks to the vboxusers group can be done automatically by creating the following file:

    /etc/udev/rules.d/99-vbox.rules

    #
    # Rules to give VirtualBox users raw access to Windows partitions
    #

    # Microsoft Reserved partition
    SUBSYSTEM=="block", ENV{ID_PART_ENTRY_TYPE}=="e3c9e316-0b5c-4db8-817d-f92df00215ae", GROUP="vboxusers"

    # Windows partition
    SUBSYSTEM=="block", ENV{ID_PART_ENTRY_TYPE}=="ebd0a0a2-b9e5-4433-87c0-68b6b72699c7", GROUP="vboxusers"

    #
    # Rules to give VirtualBox users raw access to Windows disk
    #

    # sdb
    ENV{ID_PART_TABLE_UUID}=="WINDOWS_DISK_ID_PART_TABLE_UUID", GROUP="vboxusers"

`WINDOWS_DISK_ID_PART_TABLE_UUID` must be replaced with the value obtained from `udevadm info /dev/WINDOWS_DISK` (replace `WINDOWS_DISK` with the disk containing Windows partitions). The UUIDs in these rules correspond to particular GPT partition types while the other capitalized strings are supposed to be written that way, so those does not have to be replaced.

Then the user running VirtualBox must be added to the vboxusers group. This can be done with the following command:

    # usermod -aG vboxusers VIRTUALBOX_RUNNING_USER

Replace `VIRTUALBOX_RUNNING_USER` and with the user that will run VirtualBox, which most likely will be your user.

##### Lower security option: using 'disk' group

To be able to add the VMDK file in VirtualBox Virtual Media Manager without running VirtualBox as root, the user running VirtualBox need to be in `vboxusers` and `disk` groups.

    # usermod -aG disk,vboxusers VIRTUALBOX_RUNNING_USER

Replace `VIRTUALBOX_RUNNING_USER` and with the user that will run VirtualBox, which most likely will be your user.

警告：Be aware of the potential security implications of this edit, as you are giving your user account full read-write access all storage devices owned by the disk group.

#### Setting up a separate EFI system partition

Virtual machine EFI boot files will refer to different disks than the ones in the physical EFI system partition, so VirtualBox must not make use of the latter but instead of an EFI system partition inside a dedicated virtual disk. This disk can be created with the following command:

    $ VBoxManage createmedium disk --filename VM_DIRECTORY/esp.vmdk --size 512 --format VMDK

Replace `VM_DIRECTORY` with the folder containing the virtual machine being built.

#### Adding virtual disks to the virtual machine

Configure the virtual machine storage devices (Settings panel - Storage) as following:

- add `esp.vmdk` as a SATA hard disk attached to the "SATA Port 0";
- add `windows.vmdk` as a SATA hard disk attached to the "SATA Port 1";
- mount Windows installation iso into the virtual optical drive .

注意：

- for adding a SATA hard disk use the second button on the right of the "Controller: SATA" device;
- the virtual optical drive should already be there as "Optical Drive".

#### Configuring the virtual UEFI firmware and creating Windows boot files

Now start the virtual machine and it should automatically boot from Windows installation disk. After choosing the installation locales click on the "Repair your computer" link, then choose "Troubleshoot" and then " Command Prompt" in order to launch a command prompt from the install media.

Enter the following commands to create a new GPT table in the esp.vmdk disk and install the Windows boot loader onto it using configuration from the existing Windows partition:

Open Diskpart:

    X:\ diskpart

List all disks identified by the system:

    DISKPART> list disk

The `esp.vmkd` disk should be labeled as `disk 0` due to the fact that was attached to the SATA port 0, ~512 MiB in size and unpartitioned. The `windows.vmdk` disk should be labeled as `disk 1`; note that the column "Size" displays the disk size, not the partition one.

Select the esp.vmdk disk:

    DISKPART> select Disk 0

Now create a GPT partition table, an EFI system partition, big as the whole disk, and assign to it a label and drive letter:

    DISKPART> clean
    DISKPART> convert gpt
    DISKPART> create partition efi size=500
    DISKPART> format quick fs=fat32 label="System"
    DISKPART> assign letter="S"

Check that the partition has been correctly created:

    DISKPART> list volume

Our newly created EFI system partition will be labeled as "SYSTEM" with letter as "S".

Take note of the Windows installation volume letter because it will be used in next steps. Usually its `D` but it could be different: you can infer it from its label and its size. The size is the same as the Windows installation partition size on your physical hard disk.

Exit diskpart:

    DISKPART> exit

Install the Windows boot loader into the EFI system partition.

    D:
    cd Windows\System32
    bcdboot D:\Windows /s S: /f UEFI

Now close the command prompt, power off the virtual machine and detach the Windows installation disk (from "Preferences > Devices" remove the optical disk). The virtual machine should now boot from the newly installed boot partition and load the physical Windows installation. It may show some UEFI related errors on the top of the virtual machine window and the first boot may take a while, but if everything has been done correctly you will be able to access your windows installation.

### Run an entire physical disk in VirtualBox

注意：You may refer to VirtualBox official documentation 9.8.1. Using a Raw Host Hard Disk From a Guest.

This works the same way as #Run a native Windows installation inside VirtualBox but the vmdk will contain the entire disk rather than one partition, and so you will not need to create a separate ESP or MBR partition as the one in the physical disk will be used.

Create the raw disk:

    # VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sdb

Then follow the same method as in #Run a native Windows installation inside VirtualBox for the configuration and virtual disk attachement.

### Set guest starting resolution

Typically after installing Guest Additions, a fullscreen Arch guest running X will be set to the optimal resolution for your display; however, the virtual console's framebuffer will be set to a standard, often smaller, resolution detected from VirtualBox's custom VESA driver.

To use the virtual consoles at optimal resolution, Arch needs to recognize that resolution as valid, which in turn requires VirtualBox to pass this information along to the guest OS.

First, check if your desired resolution is not already recognized by running the command (hwinfo包 need to be installed):

    hwinfo --framebuffer

If the optimal resolution does not show up, then you will need to run the `VBoxManage` tool on the host machine and add "extra resolutions" to your virtual machine (on a Windows host, go to the VirtualBox installation directory to find `VBoxManage.exe`). For example:

    $ VBoxManage setextradata "Arch Linux" "CustomVideoMode1" "1360x768x24"

The parameters "Arch Linux" and "1360x768x24" in the example above should be replaced with your virtual machine name and the desired framebuffer resolution. Incidentally, this command allows for defining up to 16 extra resolutions ("CustomVideoMode1" through "CustomVideoMode16"). Recommended resolutions are 1280x720, 1920x1080, 2048x1080, 2560x1440, 3840x2160, 1280x800, 1280x1024, 1440x900, 1600x900.

Afterwards, restart the virtual machine and run `hwinfo --framebuffer` once more to verify that the new resolutions have been recognized by your guest system (which does not guarantee they will all work, depending on your hardware limitations).

注意：As of VirtualBox 5.2, `hwinfo --framebuffer` might not show any output, but you should still be able to set a custom resolution following this procedure.

Finally, add a `video=resolution` kernel parameter to set the framebuffer to the new resolution, for example:

    video=1360x768

Additionally you may want to configure your boot loader to use the same resolution. If you use GRUB, see GRUB/Tips and tricks#Setting the framebuffer resolution.

注意：Neither the kernel parameter `vga` nor the boot loader's resolution settings (e.g. GRUB's `GRUB_GFXPAYLOAD_LINUX`) will fix the framebuffer, since they are overriden by virtue of Kernel Mode Setting. The framebuffer resolution must be set by the kernel parameter `video` as described above.

### SSH from host to guest

The network tab of the virtual machine settings contains, in "Advanced", a tool to create port forwarding. It is possible to use it to forward the Guest ssh port `22` to a Host port, e.g. `3022` :

    user@host$ ssh -p 3022 $USER@localhost

will establish a connection from Host to Guest.

#### SSHFS as alternative to shared folders

Using this port forwarding and SSHFS it is straightforward to mount the Guest filesystem onto the Host one:

    user@host$ sshfs -p 3022 $USER@localhost:$HOME ~/shared_folder

and then transfer files between both.

### Specify Host-Only Network

For security reasons, the VirtualBox network driver limits the usable subnet ranges. This will cause `E_ACCESSDENIED` errors when changing the virtual network adapter settings[5]. You can change the allowed list of networks by adding them to `/etc/vbox/networks.conf`.

For example:

         * 10.0.0.0/8 192.168.0.0/16
         * 2001:db8:1234::/48

注意：The spaces and asterisk are important.

For IPv6 it is best practice to generate a new, randomized ULA prefix.

Do not forget to reload the driver and restart VirtualBox after changing `/etc/vbox/networks.conf`:

    # modprobe -r vboxnetadp vboxnetflt
    # modprobe vboxnetadp vboxnetflt

## 故障排除

### 滑鼠鍵盤都鎖死在虛擬機裡了

這是因為你的虛擬機捕獲了鍵盤與滑鼠的輸入。只要按下右 `Ctrl` 鍵即可讓輸入焦點回到宿主系統。

如果想要不按切換鍵就能讓滑鼠在宿主機與虛擬機之間無縫切換，需要在客戶機中安裝客戶機插件。如果你的虛擬機系統是 Arch Linux，請參考 /在虛擬機中安裝 Arch Linux#安裝客戶機插件，其他系統請參閱 VirtualBox 的官方幫助文檔。

### 無法新建 64 位虛擬機

如果新建虛擬機時看不到 64 位系統選項，需先確保已在 BIOS 中啟用 CPU 虛擬化技術（通常稱作 `VT-x`）。

如果你的宿主系統是 Windows，那麼你得禁用 Hyper-V 功能，因為 Hyper-V 會妨礙 VirtualBox 使用 VT-x。[6]

### VirtualBox 圖形管理界面和主機 GTK 主題樣式不匹配

如需修改類似 VirtualBox 的 Qt 應用的外觀，請參考統一 Qt 和 GTK 應用程式的外觀。

### 無法向虛擬機鍵入 Ctrl+Alt+Fn

如果你在虛擬機安裝了某個 Linux 發行版，有時會需要按 `Ctrl+Alt+F2` 進入它的 TTY 界面，或者按 `Ctrl+Alt+Backspace` 來退出 X 會話。如果你的宿主系統也是 Linux，這些組合鍵默認會首先被宿主系統捕獲。正確的做法是按 Host Key（默認是右 `Ctrl`）加 `F2` 來向虛擬機鍵入 `Ctrl+Alt+F2`。

### USB 功能不可用

在宿主系統裡使用虛擬機的用戶需被加入到 `vboxusers` 用戶組。如果想要支持 USB 2 設備，還要安裝擴展包。此後在虛擬機的設置裡即可開啟 USB 2 支持，並能通過過濾規則來允許客體系統訪問指定的 USB 設備。

如果用 root 身份運行 `VBoxManage list usbhost` 命令也沒有列出任何 USB 設備，需要確認一下 `/etc/udev/rules.d/` 目錄裡沒有遺留的 VirtualBox 4.x 的 udev 規則。VirtualBox 5.0 起會把 udev 規則文件安裝到 `/usr/lib/udev/rules.d/` 目錄。用 `pacman -Qo /usr/lib/udev/rules.d/60-vboxdrv.rules` 命令可以查看這些 udev 文件是否已經過期。

有時某些舊 Linux 宿主系統無法自動檢測到 USB 子系統，就會出現這個錯誤：`Could not load the Host USB Proxy service: VERR_NOT_FOUND`。或者可能讓宿主機也識別不了 USB 磁碟，哪怕用戶已經加入了 vboxusers 用戶組。出現這類問題的原因是 VirtualBox 從 3.0.8 版本開始，從 usbfs 轉向使用 sysfs。如果宿主系統不支持這一改動，你可以在 shell 的啟動腳本（舉例：如果在用 bash 的話，就修改 `~/.bashrc` 文件）裡聲明這一環境變量，讓 VirtualBox 回退到舊的行為：

    ~/.bashrc

    VBOX_USB=usbfs

然後確保這行代碼對環境變量的修改生效：重新登錄，手動加載該文件，啟動一個新 shell 會話，或者乾脆重啟。

另外，還應確保用戶加入到了 `storage` 用戶組。

### USB 數據機在宿主系統不可用

如果你的客戶機正在使用 USB 數據機，殺掉虛擬機進程可能會造成它在宿主系統裡不可用。殺掉並重啟餘下的 `VBoxSVC` 進程應該可以解決這一問題。

### USB device crashes guest

If attaching a USB device to the guest causes a crash or any other erroneous behavior, try switching the USB controller from USB 2 (EHCI) to USB 3 (xHCI) or vice versa.

### 虛擬機啟動時宿主系統卡死

一般來說，這類問題都是在 VirtualBox 或 Linux 內核版本更新之後出現。降級回到前一個版本就有可能解決問題。

### 模擬信號麥克風不可用

如果從模擬信號麥克風輸入的音頻信號在宿主機可用，但在客戶機裡不可用，可以試試在宿主機上安裝 PulseAudio 之類的音頻伺服器。

如果裝了 PulseAudio 之後麥克風還是不能用，在菜單項 VirtualBox > Machine > Settings > Audio 裡把 Host Audio Driver 的值改成 ALSA Audio Driver 也許有用。

### 映像轉換成的 ISO 文件有問題

有些映像文件格式無法可靠地轉換到 ISO 格式。例如：ccd2iso包 在轉換時會忽略 .ccd 和 .sub 文件裡的信息，最終產出的 ISO 鏡像裡的文件就可能出現損壞。

為了避免這種情況，可以使用 CDemu 或類似軟體在 Linux 客戶機裡掛載光碟映像。

### 僅主機網卡創建失敗

確保所需的內核模塊都已成功加載。詳見 #加載 VirtualBox 內核模塊。

如果還是不行，點擊 文件 > 主機網絡管理器，點擊創建進行手動創建。

### 插入模塊失敗

如果你在加載模塊時遇到如下錯誤信息：

    Failed to insert 'vboxdrv': Required key not available

將模塊簽名，或者在內核配置中禁用 `CONFIG_MODULE_SIG_FORCE`。

### VBOX_E_INVALID_OBJECT_STATE (0x80BB0007)

如果虛擬機沒有正常退出，就可能出現這個錯誤。試試下面這個命令：

    $ VBoxManage controlvm virtual_machine_name poweroff

### NS_ERROR_FAILURE 且菜單項缺失

在沒有更新擴展包，導致其與新版 VirtualBox 不兼容時就會出現該報錯。

如果在創建虛擬機時選擇了 QCOW/QCOW2/QED 虛擬盤格式，有時也可能會出現這個錯誤。

如果初次啟動虛擬機時遇到下面的錯誤消息：

    Failed to open a session for the virtual machine debian.
    Could not open the medium '/home/.../VirtualBox VMs/debian/debian.qcow'.
    QCow: Reading the L1 table for image '/home/.../VirtualBox VMs/debian/debian.qcow' failed (VERR_EOF).
    VD: error VERR_EOF opening image file '/home/.../VirtualBox VMs/debian/debian.qcow' (VERR_EOF).

    Result Code:
    NS_ERROR_FAILURE (0x80004005)
    Component:
    Medium

退出 VirtualBox，把新虛擬機的文件都刪除，並且在 VirtualBox 的配置文件中找到 `MachineRegistry` 元素，從這裡刪除你所創建的格式錯誤的虛擬機（一般是其最後一個子元素）：

    ~/.config/VirtualBox/VirtualBox.xml

    ...
    <MachineRegistry>
      <MachineEntry uuid="{00000000-0000-0000-0000-000000000000}" src="/home/void/VirtualBox VMs/debian/debian.vbox"/>
      <MachineEntry uuid="{00000000-0000-0000-0000-000000000000}" src="/home/void/VirtualBox VMs/ubuntu/ubuntu.vbox"/>
      <MachineEntry uuid="{00000000-0000-0000-0000-000000000000}" src="/home/void/VirtualBox VMs/lastvmcausingproblems/lastvmcausingproblems.qcow"/>
    </MachineRegistry>
    ...

### 缺少硬體虛擬化導致 OpenBSD 不穩定

據稱在其他的虛擬機平台上，OpenBSD 可以不依賴虛擬化指令集（VT-X，AMD-V）正常運行，VirtualBox 上的 OpenBSD 則不然。具體現象是出現大量的分段錯誤（segfault）。在啟動虛擬機時加上 -norawr0 參數可能有效，例如：

    $ VBoxSDL -norawr0 -vm name_of_OpenBSD_virtual_machine

### Windows: "The specified path does not exist. Check the path and then try again."

當在 Windows 客戶機裡運行位於共享目錄裡 .exe 程序，而這一程序又需要管理員權限時，就可能出現這一錯誤信息。[7]

一個解決辦法是把文件複製到虛擬硬碟上再運行。或者直接從 UNC 路徑 (`\\vboxsvr`) 運行程序。詳見 [8]。

### Windows 8.x 出現錯誤代碼 0x000000C4

如果你在創建虛擬機時選擇了 Win 8 系統，但在啟動時還是遇到這一錯誤，可以嘗試啟用 `CMPXCHG16B` CPU 指令集。命令如下：

    $ vboxmanage setextradata virtual_machine_name VBoxInternal/CPUM/CMPXCHG16B 1

### Windows 8, 8.1 或 10 無法安裝、啟動或報錯 "ERR_DISK_FULL"

修改虛擬機設置，在菜單項 Settings > Storage > Controller:SATA 裡勾選 "Use Host I/O Cache"。

### WinXP: 顏色深度不得多於 16 位

如果只顯示 16 位色，桌面圖標看起來會模糊 / 結塊。但是將色深調高時，系統可能會將桌面解析度限制得較低，或者根本不允許改變色深。解決辦法是在 Windows XP 虛擬機裡運行 `regedit`，並寫入這一項註冊表值：

If you are running at 16-bit color depth, then the icons may appear fuzzy/choppy. However, upon attempting to change the color depth to a higher level, the system may restrict you to a lower resolution or simply not enable you to change the depth at all. To fix this, run `regedit` in Windows and add the following key to the Windows XP virtual machine's registry:

    [HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services]
    "ColorDepth"=dword:00000004

然後再去「桌面屬性」窗口裡修改色深。如果還是不見效，強制讓屏幕重繪（比如按 `Host+f` 進入全屏模式）試試。

### Windows: 開啟 3D 加速後屏幕閃爍

VirtualBox > 4.3.14 存在問題，會導致啟用 3D 加速的 Windows 虛擬機出現閃爍。r120678 版本引入了一個補丁，可以參考如下通過環境變量添加設置：

    $ CR_RENDER_FORCE_PRESENT_MAIN_THREAD=0 VirtualBox

請確保沒有 VirtualBox 服務還在運行，並參考VirtualBox bug 13653。

### 無法在 Wayland 上啟動 VirtualBox：段錯誤

該問題是由於 Qt 檢測到了 Wayland（例如 `XDG_SESSION_TYPE=wayland`），而 VirtualBox 暫不支持 Wayland。請參考 FS#58761 和 上游 bug 工單。

可以通過設置 `QT_QPA_PLATFORM=xcb` 環境變量 來禁用 Qt 平台檢測，並強制使用 X11。

為避免影響其它在 Wayland 中可以正常使用的 Qt 應用，應只在啟動 VirtualBox 時配置 `QT_QPA_PLATFORM=xcb` 環境變量。

如果 VirtualBox 是通過桌面項啟動的，請參考桌面項#編輯環境變量將 `Exec=VirtualBox ...` 開頭的一行修改為 `Exec=env QT_QPA_PLATFORM=xcb VirtualBox ...`。如果是從 shell 命令行啟動的，可以將 `virtualbox` 別名（Bash#別名）設為 `env QT_QPA_PLATFORM=xcb virtualbox`。

注意：如果你在 Wayland 下有滑鼠和鍵盤相關的問題，也可以試試上述配置。

### Random freezing in guests with Intel GPU

With Intel CPU and graphics, allocating more processors for the guest can lower render performance, thus cause random freezing. Allocating less processors can help.

### Unable to view desktop in fullscreen mode

Disable the Mini Toolbar by selecting Machine > Settings, select the User Interface tab and uncheck the Mini Toolbar checkbox

### Random crashes with Windows 10 guest operating system with Intel Tiger Lake chipset

Disable split lock detection by adding `split_lock_detect=off` to the kernel parameters.

Details are described in VirtualBox's Ticket #20180.

### Failed to save the settings when enabling Secure Boot

In VirtualBox 7.0.0, enabling Secure Boot in a virtual machine that was created in a previous VirtualBox version will fail with a nondescript error (FS#76234):

    Failed to save the settings.

The solution is to click the Reset Keys to Default button right below the Enable Secure Boot checkbox.

### Failed to start VirtualBox machine after using Android Studio emulator

KVM and VirtualBox kernel modules can be loaded but not used simultaneously. Android Studio emulator is a QEMU emulator, which uses KVM for acceleration. So Android Studio emulator and VirtualBox machine (if hardware acceleration is enabled) cannot run at the same time. We have to use one after the other stopped completely.

Sometimes, VirtualBox kernel module can still be used unexpectedly by some process, and keep all VirtualBox machines failing to start, the error message on VirtualBox GUI is "A critical error has occurred".

At this time, we can check and reload VirtualBox kernel modules using `vboxreload` as root. If it saying some modules is still be in use, you need to manually kill related process and rerun the command.

### 3D Acceleration is not working

- Make sure guest additions are installed on guest, and the host modules are installed on the host
- Make sure the guest additions and host kernel modules versions match
  - host: `modinfo vboxdrv | grep '^version:'`
  - guest: open logs of your VM, find "Guest Additions information report"
- Make sure vulkan is installed and working on the host

### VirtualBox UI elements are improperly rendered with Kvantum installed

On some configurations of Kvantum (kvantum包) with third party themes, some UI elements such as toolbars and menus are rendered black or improperly. This seems to be limited to translucent windows being enabled. See Kvantum's issue #418.

To fix this behavior, do one of:

- Disable Translucent windows under section Configure Active Theme > Compositing & General Look of Kvantum Manager.
- Add `VirtualBox,VirtualBoxVM` in Kvantum Manager, to the Configure Active Theme > Compositing & General Look > Opaque apps: menu field.
  - This makes an exception for virtualbox windows to be ignored.

### VirtualBox is taking exclusive control of an audio device, preventing PipeWire from accessing it while the virtual machine is running

By default, VirtualBox should auto-select the best audio driver. However, on PipeWire systems this often falls back to ALSA (see Pipewire issue).

It could cause journal records like these:

    pipewire[2370]: spa.audioadapter: params Spa:Enum:ParamId:EnumFormat: 1:0 (convert format) Device or reso>
    pipewire[2370]: pw.node: (alsa_output.pci-0000_00_1f.3-platform-skl_hda_dsp_generic.HiFi__Speaker__sink-6>
    pipewire[2370]: spa.alsa: '_ucm0001.hw:sofhdadsp': playback open failed: Device or resource busy

The solution is to configure VirtualBox to use the PulseAudio backend (which PipeWire will handle via pipewire-pulse):

    $ VBoxManage modifyvm "Your_virtual_machine_name" --audio-driver pulse --audio-controller hda

## 參閱

- User Guide on a single HTML page

分類：​

- 虛擬機管理
- Oracle
- 包含失效連結的頁面
- 使用「模板:風格」標記的頁面或章節

隱藏分類：​

- 使用「模板:Translateme」標記的頁面或章節

VirtualBox
新增話題