Linux VM 串口 Console 配置记录
使用串口设备可以操控网络故障或者没有配置网络下的虚拟机,相比平常使用的 graphic console 设备更方便复制粘贴。同时可以将串口输出设置保存到文件,在虚拟机崩溃时验尸。
在 hypervisor 中为虚拟机设置 serial 设备
以 KVM/libvirt/QEMU 为例,如使用 libvirt xml devices 块中配置如下:
<serial type="pty">
<target type="isa-serial" port="0">
<model name="isa-serial"/>
</target>
</serial>
虚拟机开机后,虚拟串口 backend 绑定到了宿主机上的一个 pseudo terminal(PTY),这里是 /dev/pts/4。
<serial type="pty">
<source path="/dev/pts/4"/>
<target type="isa-serial" port="0">
<model name="isa-serial"/>
</target>
<alias name="serial0"/>
</serial>
使用virsh console 可以连接到绑定的 PTY ,devname 是在配置中指定的 alias name。
$ virsh console vmname --devname serial0
添加内核命令行参数来配置 Linux 使用串口作为控制台
如果没有指定 console 设备,系统会使用第一个能作为系统控制台的设备。此时,系统首先寻找 VGA 显卡,然后寻找串口。所以如果您的系统中没有 VGA 显卡,第一个串口会自动成为控制台。
对于同时存在显卡和串口的情况,需要显式添加
console参数来确保有内核启动日志输出和可以使用串口交互登录。
以 GRUB 为例,编辑 /etc/default/grub 后使用update-grub 更新 /boot 里的 GRUB 配置。
GRUB_CMDLINE_LINUX="console=ttyS0,115200 console=tty0"
