Welcome to the Linux Foundation Forum!

LFS201 - Chapter 17 Discussion // Questions // Banter - Disk Partitioning

heiko_sheiko_s Posts: 34

So I run all these exercises on virtual machines that do not let me access the actual drives (I use LVM for all storage). How can I play around with fdisk?

Script to exercise the use of fdisk

I had to break my head a little, but eventually I came up with a solution. The script below creates a file that will hold virtual file systems created by fdisk. The file system(s) will then be mounted. At that point you could create files/folders and play around with them like with any other folder or file system that is mounted. Along the way it will stop at each step and show the command it'll run.

At the end the script removes the mount points and deletes the image file so you can start clean as a whistle.

Feel free to edit/improve the script and add more file systems to the case ... esac part.

The script must be run with "sudo" (root permissions)

#!/bin/bash
# fdisk exercise
#
# Copyright (C) 2020 Heiko Sieger
# https://heiko-sieger.info
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# Name of the image file:
file="mbrtest"
# Specify size in MBytes:
size=512
user=$(logname)

pause(){
    msg="$1"
    cmd="$2"
    echo -e "$msg\n"
    echo -e "$cmd\n"
    read -p "Press [ENTER] to continue..." wait_for_enter
    echo -e "\n"
    ${cmd}
    echo -e "\n"
}

if [ $UID -ne 0 ]; then
    pause "Run script as 'root'! Abort." "exit 1"
fi

# Create file "$file" filled with zeros ($size Mbyte)
pause "Create $file filled with zeros (512 Mbyte)" "dd if=/dev/zero of=$file bs=1M count=$size"

# Get the loop device that kpartx will mount
dev="$(kpartx -l $file | awk '{ print $NF }')"

# Mount $file as loop device
pause "Mount $file as loop device:" "kpartx -av $file"
echo -e "$dev\n"

# dev="$(lsblk -lo NAME,SIZE | egrep loop[0-9p]?[0-9] | sort -h -k 2 | awk '{ print $(NF-1) }')"

echo -e "In the next step we are going to invoke fdisk."
echo -e "Use fdisk to create partitions, change partition type, etc."
echo -e "Once you finished and checked everything, use the "w" command"
pause "to write the changes to the partition table." "fdisk $dev"

dev2="$(kpartx -l $file | awk '{ print $1 }')"
dev2=($dev2)
pause "Finished fdisk. Now we update the partition mappings:" "kpartx -u $file"

pause "Show partitions inside $file using 'fdisk':" "fdisk -l $dev"

type="$(fdisk -l $dev | egrep ${dev:5}[0-9p]?[1-9] | sort -h -k 2 | awk '{ print $(NF-1) }')"
pause "Partition type(s):\n $type\n" ""
type=($type)

for ((i=0;i<${#dev2[*]};i++)); do
    device="/dev/mapper/${dev2[i]}"
#    echo "${dev2[i]}"
#    echo -e "Device: $device\n"
    mnt="/mnt/${dev2[i]}"
    case ${type[i]} in
        0) cmd="mkfs.ext4";;
        1) cmd="mkfs.fat -v -F 12";;
        4) cmd="mkfs.fat -v -F 16";;
        6) cmd="mkfs.fat -v -F 16";;
        7) cmd="mkfs.ntfs -v";;
        NTFS) cmd="mkfs.ntfs -v";;
        FAT32) cmd="mkfs.fat -v -F 32";;
        83) cmd="mke2fs -v";;
        EFI) cmd="mkfs.fat -v -F 16";;
        *) cmd="mkfs.ext4 -v";;
    esac
    pause "Format $device as ${type[i]}:" "$cmd $device"
    pause "Create mount point:" "mkdir $mnt"
    pause "Mount partition on $mnt:" "mount $device $mnt"
    pause "Change ownership:" "chown $user:$user $mnt"
done

pause "See new partitions as loop devices using lsblk:" "lsblk"
pause "See if the partitions are mounted:" "df"
pause "Let's check /proc/mounts:" "grep loop /proc/mounts"
pause "You could now create content on the file system(s), but we unmount:" "umount /mnt/*"
pause "Remove mount points:" "rm -rf /mnt/*"
pause "Delete loop device mappings:" "kpartx -d $file"
pause "Delete $file:" "rm $file"
pause "All is back to as it was before. Done." "exit 0"
#END

Enjoy!

Comments

  • heiko_sheiko_s Posts: 34

    Dammit - I did it again. Can an administrator change the thread title? It should read:

    Chapter 17 Discussion // Questions // Banter - Disk Partitioning

    Why is there a 15 minutes limit to edit posts?

  • coopcoop Posts: 437

    Much to my surprise I was able to change the title. )

    I did not know there was a 15 minute time limit but I suspect that is intrinsic. Fcioanca may be able to comment on that.

    One thing I'd love to limit is how often people post, as sometimes people post multiple messages in a short period (like 10 in an hour) as they think this is a real time chat. We are good on this forum but not all forums get this much attention, and I don't like the posts where 10 minutes later people say, don't bother I figured it out. That should happen before they post :) When people do this I personally rate-limit my responses and introduce a delay, like a day before I answer certain people.

  • heiko_sheiko_s Posts: 34

    Thanks coop!

    In "Lab 17.3. Using losetup and parted" we learn how to use losetup. I have only had bad experiences with losetup.

    For example, issuing losetup -d ... did not remove the partitions loop1p1, loop1p2 etc.

    I redid the exercise to test using losetup -D, --detach-all which is supposed to "Detach all associated loop devices." No luck. The loop devices are still in /dev/...

    Recently I had to rewrite my rsync backup script and replace losetup with kpartx because I couldn't get losetup to work. Some update (kernel?) broke the automatic discovery and mounting of partitions using the "losetup -P" option.

    On the other hand, kpartx has worked for me flawlessly for the last 8 years or so.

  • luisviveropenaluisviveropena Posts: 544

    Hi @heiko_s ,

    So I run all these exercises on virtual machines that do not let me access
    the actual drives (I use LVM for all storage). How can I play around with fdisk?

    At least for playing with fdisk, you can create a disk image and then add it to a guest. Then you can mount it (at least it works like that in VirtualBox). Then you can play with LVM or anything you want.

    Regards,
    Luis.

  • coopcoop Posts: 437

    You can definitely add a second disk in vmware as well (and I'm sure kvm etc.) You can also "expand" the disk to a larger size and add new parititions etc. This is even easier and I've done it many times. It's like a couple of mouse clicks.

    As far as the losetup hassles, not the first time I've seen inconsistent results between distros, which among other things use different names for loop devices. I don't have a specific solution. I generally would never script anything partitioning devices as it is so easy to induce an error which bricks your system. It only makes sense if you are intending on using it to deploy numerous systems at once and then you would be extremely careful and you would not be likely to be using loopback devices. For example, even basic fdisk has varied quited a bit between distros as older and newer versions have had different defaults etc.

  • heiko_sheiko_s Posts: 34

    Here is the gdisk script. It leaves room for improvement, but offers the possibility to use LVM within a file. All except the gdisk part is semi-automatic.

    Be careful: when creating LVM volumes it will actually change the LVM entries of the OS you are running. So you should go through with the program and reverse the steps (the program does it), or reverse them manually in case you interrupted the program!

    #!/bin/bash
    # gdisk exercise
    #
    # Copyright (C) 2020 Heiko Sieger
    # https://heiko-sieger.info
    #
    # This program is free software: you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation, either version 3 of the License, or
    # (at your option) any later version.
    #
    # This program is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    # GNU General Public License for more details.
    #
    # Name of the image file:
    file="gpttest"
    # Specify size in MBytes:
    size=512
    
    #user=$(logname)
    pv_list=""
    vg_name=""
    GR='\033[1;32m' # Green
    NC='\033[0m' # No Color
    
    pause(){
        msg="$1"
        cmd="$2"
        input="$3"
        echo -e "\n$msg"
        [[ -n "$input" ]] && read -p "$input: " input garbage
        echo -e "\n${GR}$cmd${NC}\n"
        read -p "Press [ENTER] to continue..." wait_for_enter
    #    echo -e "\n"
        ${cmd}
    }
    
    if [ $UID -ne 0 ]; then
        pause "Run script as 'root'! Abort." "exit 1"
    fi
    
    # Create file "$file" filled with zeros ($size Mbyte)
    pause "Creating $file filled with zeros ($size Mbyte)." "dd if=/dev/zero of=$file bs=1M count=$size"
    
    # Get the loop device that kpartx will map
    dev="$(kpartx -l $file | awk '{ print $NF }')"
    
    # Map $file as loop device
    pause "Mapping $file as loop device." "kpartx -av $file"
    echo -e "$dev\n"
    
    echo -e "In the next step we are going to invoke gdisk."
    echo -e "Use gdisk to create partitions, change partition type, etc."
    echo -e "Once you finished and checked everything, use the "w" command"
    echo -e "to write the changes to the partition table." 
    pause "" "gdisk $dev"
    
    dev2="$(kpartx -l $file | awk '{ print $1 }')"
    dev2=($dev2)
    pause "Finished gdisk. Now we update the partition mappings." "kpartx -u $file"
    
    pause "Show partitions inside $file using 'gdisk'." "gdisk -l $dev"
    
    type="$(gdisk -l $dev | egrep [[:space:]][0-9A-F]{4}[[:space:]]{2} | awk '{ print $6 }')"
    pause "Partition type(s):\n $type\n" ""
    type=($type)
    
    for ((i=0;i<${#dev2[*]};i++)); do
        device="/dev/mapper/${dev2[i]}"
        mnt="/mnt/${dev2[i]}"
        case ${type[i]} in
            0700) cmd="mkfs.ntfs -v";;
            2700) cmd="mkfs.ntfs -v";;
            8200) cmd="mkswap";;
            8300) cmd="mke2fs -v";;
            8E00) pause "We need to create a PV (LVM) for partition type 8E00:" "pvcreate $device";
                pv_list="$pv_list $device"
                if [ -z "$vg_name" ]; then
                    rc=1;
                    while [ $rc -ne 0 ] ; do
                        pause "Now we create a VG (volume group)." "" "Enter the name of the VG";
                        vg_name=$input;
                        [[ $vg_name =~ ^[a-zA-Z0-9]+ ]] && rc=0 ;
                    done ;
                    pause "Creating VG..." "vgcreate $vg_name $device" "" ;
                    sleep 2 ;
                else
                    pause "Extending VG $vg_name..." "vgextend -A n -y -v $vg_name $device";
                fi
                rc=1;
                sleep 1 ;
                while [ $rc -ne 0 ] ; do
                    pause "Next we create a LV (logical volume)." "" "Enter the name of the LV";
                    lv_name=$input;
                    [[ $lv_name =~ ^[a-zA-Z0-9]+ ]] && rc=0 ;
                done ;
                rc=1;
                sleep 1 ;
                while [ $rc -ne 0 ] ; do
                    pause "Enter the size of the LV $lv_name." "" "Use K for Kilobytes, M for Megabytes, or G for Gigabytes (example 100M)";
                    lv_size=$input;
                    pause "Creating LV..." "lvcreate -L $lv_size -n $lv_name $vg_name" "";
                    rc=$?;
                    [[ $rc -ne 0 ]] && echo -e "Size is too big.\n";
                done ;
                pause "Listing the LVs:" "lvs";
                device="/dev/mapper/$vg_name-$lv_name";
                cmd="mkfs.ext4 -v";;
            EF00) cmd="mkfs.fat -v -F 16";;
            *) cmd="mkfs.ext4 -v";;
        esac
        pause "Formating $device as ${type[i]}" "$cmd $device"
        pause "Creating mount point" "mkdir $mnt"
        pause "Mounting partition on $mnt" "mount $device $mnt"
    #    pause "Changing ownership" "chown $user:$user $mnt"
    done
    
    pause "See new partitions as loop devices using lsblk:" "lsblk"
    pause "See if the partitions are mounted:" "df -Th"
    pause "Let's check /proc/mounts:" "grep loop /proc/mounts"
    pause "You could now create content on the file system(s), but we unmount..." "umount /mnt/*"
    pause "Removing mount points..." "rm -rf /mnt/*"
    
    if [ ! -z "$vg_name" ]; then
        pause "Removing all LVs we created..." "lvremove -A n -f -v $vg_name"
        pause "Removing the VG..." "vgremove -f -y -v $vg_name"
        pause "List the remaining VGs:" "vgs"
        pause "Removing PV$pv_list..." "pvremove -f -y -v$pv_list"
        pause "List the remaining PVs:" "pvs"
    fi
    
    pause "Deleting loop device mappings..." "kpartx -d $file"
    pause "Deleting $file..." "rm $file"
    pause "All is back to as it was before. Done." "exit 0"
    #END
    
  • GRO 108GRO 108 Posts: 13

    @heiko_s These scripts are fantastic.

    There was one concern that I had with a step in the MBR version that could potentially be too destructive.

    line:92 pause "Remove mount points:" "rm -rf /mnt/*"

    This made me think that it would be really nice to be able to comment on the script and potentially contribute suggestions. Have you thought about putting these up on GitLab or GitHub?

  • heiko_sheiko_s Posts: 34
    edited July 3

    @GRO 108 said:
    @heiko_s These scripts are fantastic.

    There was one concern that I had with a step in the MBR version that could potentially be too destructive.

    line:92 pause "Remove mount points:" "rm -rf /mnt/*"

    This made me think that it would be really nice to be able to comment on the script and potentially contribute suggestions. Have you thought about putting these up on GitLab or GitHub?

    Wow, thanks for pointing that out! You are absolutely right - this needs to be changed!

    How about adding / changing:

    mkdir /mnt/exercise
    mnt="/mnt/exercise/${dev2[i]}"
    
    pause "Remove mount points:" "rm -rf /mnt/exercise/*"
    rmdir /mnt/exercise
    

    The script was kind of a quick way to get an environment to exercise. I'm running all classes in VMs so as long as I back them up there is not much harm done. But you are right - this could wipe out somebodies most precious data.

    Unfortunately I can't edit the original post, which is too bad. I would have changed it right away.

  • GRO 108GRO 108 Posts: 13

    Yeah VMs are the way to go. I've been taking advantage of a Google Cloud free trial which has been very convenient.

    Thanks for the update.

Sign In or Register to comment.