zero of=rootfs.img bs=1M count=1024
# 格式化
mkfs.ext4 rootfs.img
# or
mkfs -t ext4 rootfs.img
# 挂载空镜像
mkdir rootfs
sudo mount rootfs.img rootfs/
# 写入文件, 保留权限
sudo cp -rfp workroot/* rootfs/
# 取消挂载
sudo umount rootfs/
# 检查文件系统并自动修复
e2fsck -p -f rootfs.img
# 使镜像紧凑
resize2fs -M rootfs.img
问题和解决
Root 能串口登录, 无法 ssh 登录
这是因为 ssh 默认禁止 root 登录, 编辑 /etc/ssh/sshd_config, 找到
#PermitRootLogin prohibit-password
替换为
PermitRootLogin yes
然后systemctl restart sshd
重启 sshd 服务
分区可用空间为0
这是因为镜像压缩后写入, 分区大小就是镜像大小, 需要通过 resize2fs /dev/[partition] 扩充分区
方案一: 使用脚本, 手工执行
创建 /usr/bin/local_resize.sh, 内容如下, chmod +x
设为可执行
#!/bin/bash
rootfs_partition=/dev/$(lsblk -l|grep /|awk '{print $1}')
logger -t "resize-disk[$$]" "resizing $rootfs_partition"
if [ "$(echo $rootfs_partition | grep "mmc")" = "" ];then
rootfs_disk=$(echo "$rootfs_partition" |sed -E -e 's/^(.*)[0-9]+/\1/g')
else
rootfs_disk=$(echo "$rootfs_partition" |sed -E -e 's/^(.*)p[0-9]+/\1/g')
fi
if [ "$rootfs_disk" = "/dev/mmcblk0" ]; then
resize2fs $rootfs_partition 2>&1 > /dev/null
else
rootfs_partition_num=$(echo "$rootfs_partition" |sed -E -e 's/^.*([0-9]+)/\1/g')
startfrom=$(fdisk -l ${rootfs_disk} -o device,start|grep ${rootfs_partition}|awk '{print $2}')
(echo d; echo $rootfs_partition_num; echo n; echo p; echo $rootfs_partition_num; echo $startfrom; echo ; echo p; echo w;) | fdisk $rootfs_disk
sync
resize2fs $rootfs_partition
fi
logger -t "resize-disk[$$]" "resized $rootfs_partition"
方案二: 使用 systemd service 在第一次启动时执行
增加 /usr/sbin/local-resize2fs.sh , chmod +x
设为可执行
#!/bin/bash
if [ ! -f /etc/first_init ]; then
rootfs_partition=/dev/$(lsblk -l|grep /|awk '{print $1}')
logger -t "resize-disk[$$]" "resizing $rootfs_partition"
if [ "$(echo $rootfs_partition | grep "mmc")" = "" ];then
rootfs_disk=$(echo "$rootfs_partition" |sed -E -e 's/^(.*)[0-9]+/\1/g')
else
rootfs_disk=$(echo "$rootfs_partition" |sed -E -e 's/^(.*)p[0-9]+/\1/g')
fi
if [ "$rootfs_disk" = "/dev/mmcblk0" ]; then
resize2fs $rootfs_partition 2>&1 > /dev/null
else
rootfs_partition_num=$(echo "$rootfs_partition" |sed -E -e 's/^.*([0-9]+)/\1/g')
startfrom=$(fdisk -l ${rootfs_disk} -o device,start|grep ${rootfs_partition}|awk '{print $2}')
#lastsector=$(fdisk -l ${rootfs_disk} -o device,end|grep ${rootfs_partition}|awk '{print $2}')
(echo d; echo $rootfs_partition_num; echo n; echo p; echo $rootfs_partition_num; echo $startfrom; echo ; echo p; echo w;) | fdisk $rootfs_disk
sync
resize2fs $rootfs_partition
fi
echo `date +%s%N` > /etc/first_init
logger -t "resize-disk[$$]" "resized $rootfs_partition"
fi
exit 0
增加service: /etc/systemd/system/resize2fs.service
[Unit]
Description=resize2fs local filesystem
Before=local-fs-pre.target
DefaultDependencies=no
[Service]
Type=oneshot
TimeoutSec=infinity
ExecStart=/usr/sbin/local-resize2fs.sh
RemainAfterExit=true
[Install]
RequiredBy=local-fs-pre.target
在 /etc/systemd/system/local-fs-pre.target.wants/ 下面增加 resize2fs.service 的软链, 使其生效
参考