qemu-alpine-ssh

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

QEMU Alpine SSH Setup

QEMU Alpine SSH 配置教程

Overview

概述

This skill provides procedural guidance for setting up QEMU virtual machines running Alpine Linux with SSH access configured. It covers VM startup, network port forwarding, Alpine system configuration, and SSH server setup.
本指南为配置SSH访问的Alpine Linux QEMU虚拟机提供分步指导,内容涵盖虚拟机启动、网络端口转发、Alpine系统配置以及SSH服务器搭建。

Diagnostic-First Approach

先诊断后操作的方法

Before attempting any QEMU setup or troubleshooting syntax, verify preconditions first:
在尝试任何QEMU配置或排查语法问题之前,请先验证前置条件:

1. Check Port Availability

1. 检查端口可用性

Before starting QEMU with port forwarding, verify the target port is not in use:
bash
undefined
在启动带端口转发的QEMU之前,先确认目标端口未被占用:
bash
undefined

Preferred methods (if available)

优先使用的方法(如果可用)

ss -tlnp | grep :2222 netstat -tlnp | grep :2222 lsof -i :2222
ss -tlnp | grep :2222 netstat -tlnp | grep :2222 lsof -i :2222

Fallback when standard tools unavailable

当标准工具不可用时的备选方案

cat /proc/net/tcp | awk '{print $2}' | grep -i ":08AE" # 08AE is hex for 2222

Port 2222 in hex is `08AE`. Common ports: 22 = `0016`, 2222 = `08AE`, 8080 = `1F90`.
cat /proc/net/tcp | awk '{print $2}' | grep -i ":08AE" # 08AE是2222的十六进制表示

2222端口的十六进制表示为`08AE`。常用端口对应:22 = `0016`,2222 = `08AE`,8080 = `1F90`。

2. Check for Existing QEMU Processes

2. 检查是否存在QEMU进程

Always verify no orphaned QEMU processes exist:
bash
undefined
请始终确认没有残留的QEMU孤儿进程:
bash
undefined

Find QEMU processes

查找QEMU进程

ps aux | grep qemu pgrep -la qemu
ps aux | grep qemu pgrep -la qemu

Kill all QEMU processes if needed

如有需要,终止所有QEMU进程

pkill -9 qemu-system pkill -9 qemu
undefined
pkill -9 qemu-system pkill -9 qemu
undefined

3. Verify ISO/Image Files Exist

3. 验证ISO/镜像文件是否存在

Confirm required files are present before starting QEMU:
bash
ls -la /path/to/alpine.iso
file /path/to/alpine.iso
在启动QEMU之前,确认所需文件已存在:
bash
ls -la /path/to/alpine.iso
file /path/to/alpine.iso

QEMU Startup Configuration

QEMU启动配置

Basic Command Structure

基础命令结构

bash
qemu-system-x86_64 \
  -m 512 \
  -cdrom /path/to/alpine.iso \
  -boot d \
  -nographic \
  -netdev user,id=net0,hostfwd=tcp::2222-:22 \
  -device virtio-net-pci,netdev=net0
bash
qemu-system-x86_64 \
  -m 512 \
  -cdrom /path/to/alpine.iso \
  -boot d \
  -nographic \
  -netdev user,id=net0,hostfwd=tcp::2222-:22 \
  -device virtio-net-pci,netdev=net0

Port Forwarding Syntax

端口转发语法

The correct hostfwd syntax is:
tcp::[host_port]-:[guest_port]
Valid examples:
  • hostfwd=tcp::2222-:22
    - Forward host 2222 to guest 22
  • hostfwd=tcp:127.0.0.1:2222-:22
    - Bind only to localhost
  • hostfwd=tcp:0.0.0.0:2222-:22
    - Bind to all interfaces
正确的hostfwd语法为:
tcp::[host_port]-:[guest_port]
有效示例:
  • hostfwd=tcp::2222-:22
    - 将主机2222端口转发至虚拟机22端口
  • hostfwd=tcp:127.0.0.1:2222-:22
    - 仅绑定到本地回环地址
  • hostfwd=tcp:0.0.0.0:2222-:22
    - 绑定到所有网络接口

Common Error: "Could not set up host forwarding rule"

常见错误:"Could not set up host forwarding rule"

This error typically means the port is already in use, NOT a syntax error. When encountering this:
  1. Do NOT iterate on syntax variations
  2. Immediately check port availability (see Diagnostic-First Approach)
  3. Kill any orphaned QEMU processes
  4. Retry with the same command
该错误通常意味着端口已被占用,而非语法错误。遇到此问题时:
  1. 不要尝试修改语法
  2. 立即检查端口可用性(参考先诊断后操作的方法)
  3. 终止所有残留的QEMU进程
  4. 使用原命令重试

Alpine Linux Configuration Steps

Alpine Linux配置步骤

1. Boot and Login

1. 启动并登录

Alpine boots to a login prompt. Login as
root
(no password initially).
Alpine启动后会显示登录提示符,使用
root
用户登录(初始无密码)。

2. Set Root Password

2. 设置Root密码

bash
passwd
bash
passwd

Enter password twice when prompted

按提示输入两次密码

undefined
undefined

3. Configure Network (if needed)

3. 配置网络(如有需要)

bash
setup-interfaces
bash
setup-interfaces

Select eth0, dhcp, no manual config, done

选择eth0,使用dhcp,不需要手动配置,完成

ifup eth0
undefined
ifup eth0
undefined

4. Configure Package Repositories

4. 配置软件源

bash
setup-apkrepos
bash
setup-apkrepos

Select a mirror (enter number) or 'f' for fastest

选择一个镜像源(输入对应编号)或按'f'选择最快的源

undefined
undefined

5. Install OpenSSH

5. 安装OpenSSH

bash
apk update
apk add openssh
bash
apk update
apk add openssh

6. Configure SSH for Root Login

6. 配置SSH允许Root登录

Edit
/etc/ssh/sshd_config
:
bash
undefined
编辑
/etc/ssh/sshd_config
bash
undefined

Enable root login with password

允许root用户密码登录

sed -i 's/#PermitRootLogin./PermitRootLogin yes/' /etc/ssh/sshd_config sed -i 's/#PasswordAuthentication./PasswordAuthentication yes/' /etc/ssh/sshd_config
undefined
sed -i 's/#PermitRootLogin./PermitRootLogin yes/' /etc/ssh/sshd_config sed -i 's/#PasswordAuthentication./PasswordAuthentication yes/' /etc/ssh/sshd_config
undefined

7. Start SSH Service

7. 启动SSH服务

bash
rc-update add sshd
rc-service sshd start
bash
rc-update add sshd
rc-service sshd start

Or simply: /etc/init.d/sshd start

或者直接执行:/etc/init.d/sshd start

undefined
undefined

Automation with Expect Scripts

使用Expect脚本自动化配置

For non-interactive setup, use expect scripts. Key considerations:
如需无交互配置,可使用Expect脚本。关键注意事项:

Script Structure

脚本结构

bash
#!/usr/bin/expect -f
set timeout 300

spawn qemu-system-x86_64 -m 512 -cdrom alpine.iso -boot d -nographic \
  -netdev user,id=net0,hostfwd=tcp::2222-:22 \
  -device virtio-net-pci,netdev=net0
bash
#!/usr/bin/expect -f
set timeout 300

spawn qemu-system-x86_64 -m 512 -cdrom alpine.iso -boot d -nographic \
  -netdev user,id=net0,hostfwd=tcp::2222-:22 \
  -device virtio-net-pci,netdev=net0

Wait for login prompt

等待登录提示符

expect "login:" send "root\r"
expect "login:" send "root\r"

Continue with setup commands...

继续执行配置命令...

expect "# " send "passwd\r" expect "New password:" send "password123\r" expect "Retype password:" send "password123\r"
expect "# " send "passwd\r" expect "New password:" send "password123\r" expect "Retype password:" send "password123\r"

IMPORTANT: End with 'interact' not 'interac)' or other typos

重要:结尾使用'interact',不要写成'interac)'或其他拼写错误

interact
undefined
interact
undefined

Expect Script Best Practices

Expect脚本最佳实践

  • Set adequate timeout (300+ seconds for network operations)
  • Include error handling for network timeouts during
    apk update
  • Verify script syntax before execution (check for typos like
    interac)
    )
  • Use explicit
    \r
    for carriage returns, not
    \n
  • 设置足够长的超时时间(网络操作建议300秒以上)
  • apk update
    过程中的网络超时添加错误处理
  • 执行前验证脚本语法(检查是否有
    interac)
    这类拼写错误)
  • 使用明确的
    \r
    表示回车,不要用
    \n

Verification Strategies

验证方法

Verify SSH Connectivity

验证SSH连通性

From the host:
bash
ssh -p 2222 -o StrictHostKeyChecking=no root@localhost
在主机上执行:
bash
ssh -p 2222 -o StrictHostKeyChecking=no root@localhost

Or

或者

ssh -p 2222 -o StrictHostKeyChecking=no root@127.0.0.1
undefined
ssh -p 2222 -o StrictHostKeyChecking=no root@127.0.0.1
undefined

Verify Port Forwarding is Active

验证端口转发是否生效

bash
undefined
bash
undefined

Check QEMU process shows hostfwd

检查QEMU进程是否包含hostfwd配置

ps aux | grep qemu | grep hostfwd
ps aux | grep qemu | grep hostfwd

Check port is listening

检查端口是否处于监听状态

ss -tlnp | grep 2222
undefined
ss -tlnp | grep 2222
undefined

Verify SSH Service in Guest

验证虚拟机内的SSH服务

Inside the Alpine VM:
bash
rc-service sshd status
netstat -tlnp | grep :22
在Alpine虚拟机中执行:
bash
rc-service sshd status
netstat -tlnp | grep :22

Common Pitfalls

常见误区

1. Orphaned QEMU Processes

1. 残留的QEMU进程

After killing a QEMU session, orphaned processes may still hold ports. Always run
pkill qemu-system
before retrying failed commands.
终止QEMU会话后,残留的进程可能仍占用端口。在重试失败的命令前,务必执行
pkill qemu-system

2. Premature Syntax Debugging

2. 过早调试语法

When port forwarding fails, the instinct is to try different syntax variations. This wastes time. The hostfwd syntax is well-documented and rarely the issue—check port availability first.
当端口转发失败时,人们往往会尝试修改语法,这只会浪费时间。hostfwd语法是有明确文档的,很少出现问题——请先检查端口可用性。

3. Missing Service Enablement

3. 未启用服务

Installing openssh is not enough. The service must be:
  • Started:
    rc-service sshd start
  • Enabled for boot:
    rc-update add sshd
仅安装openssh是不够的,还需要:
  • 启动服务:
    rc-service sshd start
  • 设置开机自启:
    rc-update add sshd

4. SSH Configuration Not Applied

4. SSH配置未生效

After modifying
/etc/ssh/sshd_config
, restart the service:
bash
rc-service sshd restart
修改
/etc/ssh/sshd_config
后,需要重启服务:
bash
rc-service sshd restart

5. Network Not Configured

5. 未配置网络

Alpine minimal ISO does not auto-configure networking. Run
setup-interfaces
and
ifup eth0
before attempting to install packages.
Alpine最小化ISO不会自动配置网络。在尝试安装软件包前,请先执行
setup-interfaces
ifup eth0

6. Repository Not Configured

6. 未配置软件源

apk update
will fail without configured repositories. Run
setup-apkrepos
first.
未配置软件源的话,
apk update
会失败。请先执行
setup-apkrepos

Troubleshooting Checklist

故障排查清单

When SSH connection fails, check in order:
  1. Is QEMU running? (
    ps aux | grep qemu
    )
  2. Is the host port listening? (
    ss -tlnp | grep 2222
    )
  3. Is the guest network up? (In VM:
    ip addr
    )
  4. Is SSH service running? (In VM:
    rc-service sshd status
    )
  5. Is root login permitted? (Check
    /etc/ssh/sshd_config
    )
  6. Is the password set? (Try
    passwd
    again in VM)
当SSH连接失败时,请按以下顺序检查:
  1. QEMU是否在运行?(执行
    ps aux | grep qemu
  2. 主机端口是否在监听?(执行
    ss -tlnp | grep 2222
  3. 虚拟机网络是否正常?(在虚拟机内执行
    ip addr
  4. SSH服务是否在运行?(在虚拟机内执行
    rc-service sshd status
  5. 是否允许Root登录?(检查
    /etc/ssh/sshd_config
  6. 是否设置了密码?(在虚拟机内重新执行
    passwd

Resource Cleanup

资源清理

After completing tasks, clean up:
bash
undefined
完成任务后,清理资源:
bash
undefined

Kill QEMU processes

终止QEMU进程

pkill qemu-system
pkill qemu-system

Verify ports released

验证端口已释放

ss -tlnp | grep 2222 # Should return nothing
ss -tlnp | grep 2222 # 应无输出

Remove temporary files if created

删除临时创建的文件

rm -f /tmp/alpine-setup.exp
undefined
rm -f /tmp/alpine-setup.exp
undefined