qemu-startup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

QEMU VM Startup Skill

QEMU虚拟机启动指南

This skill provides procedural guidance for starting QEMU virtual machines with serial console access, particularly for tasks involving ISO boot, telnet connectivity, and headless operation.
本指南为启动带串口控制台访问的QEMU虚拟机提供流程指导,尤其适用于涉及ISO引导、telnet连接和无界面运行的任务。

Pre-Flight Checks (Critical First Step)

启动前检查(首要关键步骤)

Before attempting any QEMU operations, verify all prerequisites systematically. Skipping this step leads to iterative failures.
在执行任何QEMU操作前,请系统地校验所有前置条件,跳过这一步会导致反复失败。

Tool Availability Check

工具可用性检查

Verify available tools before planning the approach:
bash
undefined
在规划方案前先校验可用工具:
bash
undefined

Check QEMU installation

检查QEMU安装情况

which qemu-system-x86_64 || which qemu-system-i386
which qemu-system-x86_64 || which qemu-system-i386

Check for process management tools (availability varies by environment)

检查进程管理工具(可用性随环境变化)

which ps pkill pgrep kill 2>/dev/null
which ps pkill pgrep kill 2>/dev/null

Check for network diagnostic tools

检查网络诊断工具

which nc netstat ss lsof 2>/dev/null
which nc netstat ss lsof 2>/dev/null

Check for telnet client

检查telnet客户端

which telnet

Adapt the strategy based on which tools are actually available in the environment.
which telnet

请根据环境中实际可用的工具调整操作策略。

KVM Availability Check

KVM可用性检查

Never assume KVM is available. Check before using
-enable-kvm
:
bash
undefined
绝对不要假设KVM可用,在使用
-enable-kvm
前先检查:
bash
undefined

Check if KVM module is loaded

检查KVM模块是否已加载

ls /dev/kvm 2>/dev/null && echo "KVM available" || echo "KVM not available"
ls /dev/kvm 2>/dev/null && echo "KVM available" || echo "KVM not available"

Alternative check

替代检查方式

grep -E '(vmx|svm)' /proc/cpuinfo > /dev/null && echo "CPU supports virtualization"

If KVM is not available, omit the `-enable-kvm` flag entirely rather than letting it fail.
grep -E '(vmx|svm)' /proc/cpuinfo > /dev/null && echo "CPU supports virtualization"

如果KVM不可用,请完全省略`-enable-kvm`参数,避免命令执行失败。

Resource Verification

资源校验

bash
undefined
bash
undefined

Verify the ISO/disk image exists and is readable

校验ISO/磁盘镜像存在且可读

ls -la /path/to/image.iso
ls -la /path/to/image.iso

Check if the target port is already in use

检查目标端口是否已被占用

Use whichever tool is available:

使用任意可用工具:

nc -z localhost PORT 2>/dev/null && echo "Port in use"
nc -z localhost PORT 2>/dev/null && echo "Port in use"

or

netstat -tuln | grep PORT
netstat -tuln | grep PORT

or

ss -tuln | grep PORT
undefined
ss -tuln | grep PORT
undefined

QEMU Command Construction

QEMU命令构建

Build the correct command from the start by gathering all necessary information first.
先收集所有必要信息,从一开始就构建正确的命令。

Essential Parameters for Serial Console Access

串口控制台访问的核心参数

For headless operation with telnet serial console:
bash
qemu-system-x86_64 \
    -m 512 \                           # Memory (adjust as needed)
    -cdrom /path/to/image.iso \        # Boot ISO
    -nographic \                       # No graphical output
    -serial telnet:localhost:PORT,server,nowait \  # Serial on telnet
    -monitor none                      # Disable QEMU monitor on stdio
针对带telnet串口控制台的无界面运行场景:
bash
qemu-system-x86_64 \
    -m 512 \                           # 内存(按需调整)
    -cdrom /path/to/image.iso \        # 引导ISO
    -nographic \                       # 无图形输出
    -serial telnet:localhost:PORT,server,nowait \  # 串口绑定telnet
    -monitor none                      # 禁用stdio上的QEMU monitor

Common Parameter Pitfalls

常见参数坑点

IssueCauseSolution
QEMU monitor prompt instead of serial consoleMissing
-monitor none
or conflicting
-nographic
settings
Add
-monitor none
explicitly
"Port already in use" errorPrevious QEMU instance still runningClean up existing processes first
VM hangs at bootKVM flag on system without KVMRemove
-enable-kvm
No output visibleSerial console not properly configuredEnsure
-serial
points to accessible telnet port
问题原因解决方案
出现QEMU monitor提示符而非串口控制台缺少
-monitor none
参数或
-nographic
配置冲突
显式添加
-monitor none
参数
报错「端口已被占用」之前的QEMU实例仍在运行先清理现有进程
虚拟机启动时挂起不支持KVM的系统上使用了KVM参数移除
-enable-kvm
参数
无可见输出串口控制台配置不正确确保
-serial
指向可访问的telnet端口

Conditional KVM Usage

KVM条件使用

bash
undefined
bash
undefined

Build command conditionally

条件构建命令

if [ -e /dev/kvm ]; then KVM_FLAG="-enable-kvm" else KVM_FLAG="" fi
qemu-system-x86_64 $KVM_FLAG -m 512 ...
undefined
if [ -e /dev/kvm ]; then KVM_FLAG="-enable-kvm" else KVM_FLAG="" fi
qemu-system-x86_64 $KVM_FLAG -m 512 ...
undefined

Process Management and Cleanup

进程管理与清理

Idempotent Startup Procedure

幂等启动流程

Before starting a new QEMU instance, ensure no conflicting processes exist:
bash
undefined
在启动新的QEMU实例前,确保不存在冲突进程:
bash
undefined

Find existing QEMU processes (use available tools)

查找现有QEMU进程(使用可用工具)

ps aux | grep qemu | grep -v grep
ps aux | grep qemu | grep -v grep

If pkill available:

如果有pkill可用:

pkill -f "qemu.*PORT" 2>/dev/null
pkill -f "qemu.*PORT" 2>/dev/null

If only kill available, find PID first:

如果只有kill可用,先查找PID:

Then: kill PID

然后执行:kill PID

Wait briefly for port release

短暂等待端口释放

sleep 2
sleep 2

Verify port is free before starting

启动前校验端口已空闲

undefined
undefined

Background Process Tracking

后台进程跟踪

When running QEMU in background:
  1. Record the process ID immediately after starting
  2. Store the background job identifier if using shell job control
  3. Verify the process is actually running after starting
  4. Keep track of which attempt/process is the active one
在后台运行QEMU时:
  1. 启动后立即记录进程ID
  2. 如果使用shell作业控制,请存储后台作业标识符
  3. 启动后校验进程确实在运行
  4. 跟踪当前运行的是哪次启动的进程

Readiness Verification

就绪校验

Intelligent Polling (Preferred over Fixed Sleep)

智能轮询(优于固定时长休眠)

Instead of arbitrary
sleep
durations, poll for actual readiness:
bash
undefined
不要使用任意时长的
sleep
,而是轮询实际就绪状态:
bash
undefined

Poll for port availability with timeout

带超时的端口可用性轮询

MAX_WAIT=60 WAITED=0 while ! nc -z localhost PORT 2>/dev/null; do sleep 2 WAITED=$((WAITED + 2)) if [ $WAITED -ge $MAX_WAIT ]; then echo "Timeout waiting for VM" exit 1 fi done echo "Port is listening after ${WAITED}s"
undefined
MAX_WAIT=60 WAITED=0 while ! nc -z localhost PORT 2>/dev/null; do sleep 2 WAITED=$((WAITED + 2)) if [ $WAITED -ge $MAX_WAIT ]; then echo "Timeout waiting for VM" exit 1 fi done echo "Port is listening after ${WAITED}s"
undefined

Connection Verification

连接校验

After port is listening, verify actual service readiness:
bash
undefined
端口开始监听后,校验服务实际就绪:
bash
undefined

Test telnet connection and look for expected output

测试telnet连接并查找预期输出

Use timeout to avoid hanging

使用timeout避免挂起

timeout 10 telnet localhost PORT
timeout 10 telnet localhost PORT

For automated verification, check for login prompt

自动化校验可检查登录提示

echo "" | timeout 5 telnet localhost PORT 2>&1 | grep -i "login"
undefined
echo "" | timeout 5 telnet localhost PORT 2>&1 | grep -i "login"
undefined

Verification Strategies

校验策略

Layered Verification Approach

分层校验方法

  1. Process verification: Confirm QEMU process is running
  2. Port verification: Confirm telnet port is listening
  3. Connection verification: Confirm telnet connection succeeds
  4. Service verification: Confirm expected output (login prompt, shell, etc.)
Perform each layer before proceeding to avoid false positives.
  1. 进程校验:确认QEMU进程正在运行
  2. 端口校验:确认telnet端口处于监听状态
  3. 连接校验:确认telnet连接可以成功建立
  4. 服务校验:确认返回预期输出(登录提示、shell等)
继续操作前完成每一层校验,避免误判。

State Reconciliation

状态对齐

If multiple startup attempts were made, explicitly identify which process is serving connections:
bash
undefined
如果进行了多次启动尝试,请显式识别当前提供服务的进程:
bash
undefined

Find process listening on the port

查找监听对应端口的进程

lsof -i :PORT # if available
lsof -i :PORT # 如果可用

or

netstat -tlnp | grep PORT
netstat -tlnp | grep PORT

or

ss -tlnp | grep PORT
undefined
ss -tlnp | grep PORT
undefined

Common Mistakes to Avoid

需要避免的常见错误

  1. Assuming tool availability: Always check for
    ps
    ,
    pkill
    ,
    ss
    ,
    nc
    before using them
  2. Premature KVM usage: Check
    /dev/kvm
    exists before adding
    -enable-kvm
  3. Incomplete cleanup: Verify process termination and port release before restarting
  4. Arbitrary sleep times: Use polling with readiness checks instead of fixed delays
  5. Unclear process state: Track which background process is actually running
  6. Monitor/serial confusion: Understand that
    -nographic
    alone may show QEMU monitor; use
    -monitor none
    for clean serial output
  7. Multiple redundant verifications: Design verification sequence once, execute systematically
  1. 假设工具可用:使用
    ps
    pkill
    ss
    nc
    等工具前务必先检查可用性
  2. 提前使用KVM参数:添加
    -enable-kvm
    前先检查
    /dev/kvm
    是否存在
  3. 清理不完整:重启前校验进程已终止、端口已释放
  4. 使用固定休眠时长:用带就绪校验的轮询替代固定延迟
  5. 进程状态不清晰:跟踪实际运行的后台进程
  6. 混淆monitor和串口:要知道仅
    -nographic
    可能会显示QEMU monitor,如需纯净串口输出请添加
    -monitor none
  7. 冗余校验过多:一次设计好校验顺序,按流程系统执行

Decision Framework

决策框架

Start
  ├─► Pre-flight checks pass?
  │     No ──► Adapt approach based on available tools
  │     Yes ──► Continue
  ├─► KVM available?
  │     No ──► Omit -enable-kvm flag
  │     Yes ──► Include -enable-kvm flag
  ├─► Port already in use?
  │     Yes ──► Clean up existing processes, wait for port release
  │     No ──► Continue
  ├─► Start QEMU with complete command
  ├─► Poll for port readiness (with timeout)
  ├─► Verify connection and expected output
  └─► Confirm final state explicitly
开始
  ├─► 启动前检查是否通过?
  │     否 ──► 根据可用工具调整方案
  │     是 ──► 继续
  ├─► KVM是否可用?
  │     否 ──► 省略-enable-kvm参数
  │     是 ──► 加入-enable-kvm参数
  ├─► 端口是否已被占用?
  │     是 ──► 清理现有进程,等待端口释放
  │     否 ──► 继续
  ├─► 使用完整命令启动QEMU
  ├─► 轮询端口就绪状态(带超时)
  ├─► 校验连接和预期输出
  └─► 显式确认最终状态