Monthly Archives: 10月 2019

在openwrt上运行qemu

1.编译的时候需要选择包:

kmod-tun qemu-bridge-helper qemu-x86_64-softmmu kmod-kvm-intel

2.进入系统以后挂载光盘

root@horee:/srv/iso# mkdir /mnt/cdrom
root@horee:/srv/iso# mount archlinux-2022.01.01-x86_64.iso /mnt/cdrom

3.拷贝启动文件

root@horee:/srv/iso# cp -r /mnt/cdrom/arch/boot/x86_64 ./
root@horee:/srv/iso# mv x86_64 boot

4.创建磁盘镜像

root@horee:/srv/iso# qemu-img create -f qcow2 /srv/sys/vmSrv/vmSrv.img 10G

5.启动安装光盘

root@horee:/srv/iso# qemu-system-x86_64 -enable-kvm -cpu host -smp 2 -m 4G \
    -device virtio-net-pci,mac=E2:F2:6A:01:9D:C9,netdev=br0 \
    -netdev bridge,br=br-lan,id=br0 \
    -cdrom archlinux-2022.01.01-x86_64.iso \
    -boot order=d -drive file=/srv/sys/vmSrv/vmSrv.img,format=qcow2,if=virtio \
    -curses \
    -nographic

6.按照archlinux的安装流程进行安装

进入安装菜单使用tab进去启动编辑命令,然后追加下面的配置

console=ttyS0,115200

———————————-

7.运行安装好的OS

qemu-system-x86_64 -enable-kvm -cpu host -smp 2 -m 4G \
    -device virtio-net-pci,mac=E2:F2:6A:01:9D:C9,netdev=br0 \
    -netdev bridge,br=br-lan,id=br0 \
    -boot order=d -drive file=/srv/sys/vmSrv/vmSrv.img,format=qcow2,if=virtio \
    -curses \
    -nographic

8.增加grub的console输出转发

nano -w /etc/default/grub
...
GRUB_TERMINAL_INPUT="console serial"
...
GRUB_TERMINAL_OUTPUT="gfxterm serial"
...
GRUB_SERIAL_COMMAND="serial --unit=0 --speed=115200"

9.启动脚本

#!/bin/sh /etc/rc.common

START=99
STOP=1

qemu_pidfile="/var/run/qemu.pid"

boot() {
    return 0
}

start() {
    qemu-system-x86_64 -enable-kvm -cpu host -smp 2 -m 4G \
        -device virtio-net-pci,mac=E2:F2:6A:01:9D:C9,netdev=br0 \
        -netdev bridge,br=br-lan,id=br0 \
        -qmp tcp:0.0.0.0:4488,server,nowait \
        -boot order=d -drive file=/srv/sys/vmSrv/vmSrv.img,format=qcow2,if=virtio \
        -daemonize &> /var/log/qemu.log

    /usr/bin/pgrep qemu-system-x86_64 > $qemu_pidfile
    echo "QEMU: Started VM with PID $(cat $qemu_pidfile)."
}

stop() {
    echo "QEMU: Sending 'system_powerdown' to VM with PID $(cat $qemu_pidfile)."
    nc 172.16.1.1 4488 <<QMP
    { "execute": "qmp_capabilities" }
    { "execute": "system_powerdown" }
QMP

    if [ -e $qemu_pidfile ]; then
                if [ -e /proc/$(cat $qemu_pidfile) ]; then
                        echo "QEMU: Waiting for VM shutdown."
                        while [ -e /proc/$(cat $qemu_pidfile) ]; do sleep 1s; done
                        echo "QEMU: VM Process $(cat $qemu_pidfile) finished."
                else
                        echo "QEMU: Error: No VM with PID $(cat $qemu_pidfile) running."
                fi
                rm -f $qemu_pidfile
    else
                echo "QEMU: Error: $qemu_pidfile doesn't exist."
    fi
}