yangxuan8282 / phicomm-n1

614 stars 107 forks source link

怎么备份u盘的镜像到电脑~~ #8

Closed ghost closed 5 years ago

ghost commented 5 years ago

用usb image tool 备份出来的尺寸 就是u盘的尺寸,请问如何备份的和大佬发布的镜像一样的尺寸?

ghost commented 5 years ago

U盘里写的是alpine 的镜像~~ 配置好了 想备份出来

yangxuan8282 commented 5 years ago

在我之前写的这个脚本 基础上改了一下:

#!/bin/bash
#
# backup scripts for phicomm n1, only work for my alpine image 
# usage: chmod +x bkup_n1.sh && sudo ./bkup_n1.sh
# 

set -xe

die() {
    printf '\033[1;31mERROR:\033[0m %s\n' "$@" >&2  # bold red
    exit 1
}

if [ "$(id -u)" -ne 0 ]; then
    die 'This script must be run as root!'
fi

which rsync > /dev/null || die 'please install rsync first'
which sfdisk > /dev/null || die 'please install sfdisk first'

BUILD_DATE="$(date +%Y-%m-%d)"

: ${OUTPUT_IMG:="${BUILD_DATE}-n1-bkup.img"}

: ${SRCDIR:="$(findmnt / -o source -n | sed -E 's/p?2$//')"}

cd "$(dirname "$0")"

DEST=$(pwd)

USED_ROOT_SIZE=$(df | grep $(findmnt / -o source -n) | awk 'END {print $3}')

IMAGE_SIZE=$(( $USED_ROOT_SIZE * 3000 ))

fallocate -l ${IMAGE_SIZE} "$OUTPUT_IMG"

sfdisk -d $SRCDIR | sfdisk --force "$OUTPUT_IMG"

do_format() {
    mkfs.vfat "$BOOT_DEV"
    mkfs.ext4 "$ROOT_DEV"
    mkdir -p mnt
    mount "$ROOT_DEV" mnt
    mkdir -p mnt/boot
    mount "$BOOT_DEV" mnt/boot
}

umounts() {
    umount mnt/boot
    umount mnt
    losetup -d "$LOOP_DEV"
}

migrate_system() {
    rsync -aAXv --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","${DEST}/${OUTPUT_IMG}","${DEST}/mnt/","/lost+found"} / ${DEST}/mnt
}

LOOP_DEV=$(losetup --partscan --show --find "${OUTPUT_IMG}")
BOOT_DEV="$LOOP_DEV"p1
ROOT_DEV="$LOOP_DEV"p2

do_format

BOOT_UUID=$(blkid ${BOOT_DEV} | cut -f 2 -d '"')
ROOT_UUID=$(blkid ${ROOT_DEV} | cut -f 2 -d '"')

migrate_system

echo "dtb_name=/dtbs/meson-gxl-s905d-phicomm-n1.dtb
bootargs=root=UUID=${ROOT_UUID} rootflags=data=writeback rw console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 
" | tee ${DEST}/mnt/boot/uEnv.ini

echo "UUID=${BOOT_UUID}  /boot           vfat    defaults          0       2" > ${DEST}/mnt/etc/fstab

# recreate triggers

echo "/usr/bin/resize2fs-once; rm -f /etc/local.d/resize2fs-once.start" > ${DEST}/mnt/etc/local.d/resize2fs-once.start
chmod +x ${DEST}/mnt/etc/local.d/resize2fs-once.start

umounts

cat >&2 <<-EOF
    ---
    Backup is complete
    Restore with: dd if=${OUTPUT_IMG} of=/dev/TARGET_DEV bs=4M

EOF
ghost commented 5 years ago

谢谢~~

yangxuan8282 commented 5 years ago

这样脚本要先安装 sfdisk 和 rsync

sudo apk add sfdisk rsync
ghost commented 5 years ago

https://blog.csdn.net/u013451404/article/details/80552765 我找到了一个这个 ,但是这样子 弄出来的镜像的确很小,但是改变了分区的尺寸,重写进u盘,不会自动扩容了~~

yangxuan8282 commented 5 years ago

我的这个脚本生成的镜像分区和备份前是一致的,而且可以自动扩展分区,不过预留的空间会大一点,只支持我的alpine镜像,你可以直接在 n1 上运行,或者把写入镜像的优盘插到别的 linux 电脑上运行(假设设备是 /dev/sdb): SRCDIR=/dev/sdb ./bkup_n1.sh

ghost commented 5 years ago

多谢大佬~~