#!/bin/bash
function fstab(){
for fs in $(blkid | grep -E -o '/dev/[^:]+'|grep $DISK); do
UUID=$(blkid -s UUID -o value "$fs")
FS_TYPE=$(blkid -s TYPE -o value "$fs")
if [[ "$fs" != "/dev/sda1" && "$fs" != "/dev/sda2" && "$fs" != "/dev/sda3" ]]; then
echo "UUID=$UUID $FS_TYPE defaults 0 2"
fi
done
}
# 设置变量
NAME="jammy"
DISK="/dev/vdb"
BOOT_PART="${DISK}1"
SWAP_PART="${DISK}2"
ROOT_PART="${DISK}3"
apt update -y
apt install debootstrap arch-install-scripts parted -y
parted ${DISK} --script -- mklabel gpt
parted ${DISK} mkpart primary fat32 1MiB 512MiB
parted ${DISK} mkpart primary linux-swap 512MiB 1GiB
parted ${DISK} mkpart primary ext4 1MiB 100%
# 格式化分区
mkfs.vfat -F32 $BOOT_PART
mkfs.ext4 -F $ROOT_PART
mkswap $SWAP_PART
swapon $SWAP_PART
mkdir -p /mnt/boot
mount $ROOT_PART /mnt/
mount $BOOT_PART /mnt/boot
# 使用 debootstrap 安装基本系统
debootstrap --arch amd64 $NAME /mnt/ http://archive.ubuntu.com/ubuntu/
mount -t proc /proc /mnt/proc
mount --bind /dev /mnt/dev
mount --bind /sys /mnt/sys
#更新设置系统内核和配置
chroot /mnt/ echo "root:password" | chpasswd
chroot /mnt/ apt -y update
chroot /mnt/ apt -y upgrade
chroot /mnt/ apt -y install --no-install-recommends linux-image-generic linux-firmware initramfs-tools
chroot /mnt/ apt -y install efibootmgr
chroot /mnt/ apt -y install grub2-common
chroot /mnt/ apt -y install grub-efi-amd64
chroot /mnt/ apt -y install grub-pc
chroot /mnt/ systemctl enable systemd-networkd
chroot /mnt/ grub-install $DISK
chroot /mnt/ grub-mkconfig -o /boot/grub/grub.cfg
chroot /mnt/ update-grub
#chroot /mnt/ grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=ubuntu --recheck
cat>/mnt/etc/apt/sources.list<<EOF
deb http://archive.ubuntu.com/ubuntu ${NAME} main
deb http://archive.ubuntu.com/ubuntu ${NAME} ${NAME}-security main
deb http://archive.ubuntu.com/ubuntu ${NAME} ${NAME}-updates main
EOF
cat>/mnt/etc/systemd/network/10-eth0.network<<EOF
[Match]
Name=eth0
[Network]
DHCP=yes
EOF
# 配置网络、主机名、fstab等(可根据需要添加)
fstab > /mnt/etc/fstab
echo "ubuntu" > /mnt/etc/hostname
cat <<EOL > /mnt/etc/network/interfaces
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet dhcp
EOL
swapoff $SWAP_PART
for i in /dev /proc /sys /boot /; do umount /mnt$i; done ## 卸载挂载
echo "Ubuntu installation setup completed on $DISK"