SD/TF 卡镜像文件(.img)重新挂载、文件清理与修改方法

SD/TF 卡镜像文件(.img)重新挂载、文件清理与修改方法

img 文件来源于arm架构ubuntu系统,在windows上使用Win32DiskImager读取

检查 img 文件结构

使用 fdisk 查看分区布局,确定每个分区的起始扇区和类型。

fdisk -l your_image.img

输出示例:

Disk your_image.img: 5.65 GiB, 6067884544 bytes, 11851337 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xe830825cDevice                     Boot  Start      End  Sectors  Size Id Type
your_image.img1        2048   526335   524288  256M 83 Linux
your_image.img2      526336 11851336 11325001  5.4G 83 Linux

根分区通常是最大的 Linux 分区(如 img2),其起始扇区为 526336。

/boot 分区(若有)通常是第一个分区(如 img1),起始扇区 2048。

计算分区偏移量

偏移量(字节)= 起始扇区 × 512(扇区大小)。

根分区偏移 = 526336 × 512 = 269484032

/boot 分区偏移 = 2048 × 512 = 1048576

挂载根分区(读写模式)

sudo mkdir -p /mnt/arm_rootfs
sudo mount -o loop,offset=269484032 your_image.img /mnt/arm_rootfs

验证挂载:ls /mnt/arm_rootfs 应看到 bin, etc, home, usr, var...

准备跨架构 chroot 环境

在 x86 主机上操作 ARM 镜像需安装 QEMU 用户态模拟器:

sudo apt update && sudo apt install -y qemu-user-static
sudo cp /usr/bin/qemu-arm-static /mnt/arm_rootfs/usr/bin/

进入 chroot 环境

sudo chroot /mnt/arm_rootfs /bin/bash

此时提示符变为 root@host:/#。

常用清理操作(释放空间)

清除 APT 缓存:apt-get clean

清理日志文件(除 journal 外):

rm -rf /var/log/*.log /var/log/*/*.log /var/log/*/*/*.log 2>/dev/null

清理 systemd journal(通常占用最大):

先查看大小:du -sh /var/log/journal

删除:rm -rf /var/log/journal/*

清理命令历史:

rm -f /root/.bash_history /home/*/.bash_history

其他可清理目录(按需):

/tmp/*/var/tmp/*

/var/cache/apt/archives/*.deb

退出 chroot 并清理临时文件

exit
sudo rm /mnt/arm_rootfs/usr/bin/qemu-arm-static

卸载镜像

sudo umount /mnt/arm_rootfs
sudo rmdir /mnt/arm_rootfs

最后可执行 sync 确保数据落盘。

检查清理后的镜像完整性

检查分区表:fdisk -l your_image.img

检查根文件系统(用 losetup 偏移):

sudo losetup -f -o 269484032 your_image.img
sudo losetup -l          # 查看分配的设备名,如 /dev/loop18
sudo e2fsck -f -p /dev/loop18
# 输出 rootfs: 160442/333696 files (0.6% non-contiguous), 1083568/1415625 blocks# 卸载
sudo losetup -d /dev/loop18

可选:挂载根分区并浏览 /boot 等目录检查关键文件是否存在。