Backtrack:  
 
by lunarg on April 24th 2019, at 13:47

Sometimes, when working on servers, you may need an USB stick to get some data over quickly. If you're working remotely on servers in a datacenter somewhere, this may not be easy. Fortunately, the remote management tools such as HPE's iLO or Dell's iDRAC provide the ability to connect virtual removable media, allowing you to map an image file as a "virtual USB stick". Although this is very neat, it still leaves you with one issue: how to get your files on such a removable media image. There are several useful tools which allow you to quickly create an USB image but one such method can also be achieved on linux systems with some of the native tools present.

The easiest method would be to use kpartx. This may not be installed by default on your distro but is usually available out of the box through the package repository. kpartx is a command-line tool which allows you to refresh and manipulate partitions, whether they are real or virtual (e.g. you would also use kpartx to refresh the kernel partition table after repartitioning a disk that's still in use).

The procedure

To create an USB image, first create an empty file. You'll need to size the file to the maximum size of the image file, so if you want a 32MB USB image, you'll create an empty file of 32MB in size.

dd if=/dev/zero of=./usb.img bs=1024 count=32768

Next, partition the image like you would a real disk, using fdisk or some other partitioning tool.

fdisk usb.img

Use kpartx to make the partitions in the image available as device nodes:

kpartx -a usb.img

This, in fact, leverages the native loopback device support, creating a loopback device from your image file, then refreshing the kernel partitioning table to make the partitions in your image file available as device nodes (taken care of by udev).

Create the filesystems on your partitions (e.g. for the first partition):

mkfs.vfat /dev/mapper/loop0p1

If you have multiple partitions, change device nodes accordingly. The example above formats the first partition inside the image file using FAT32.

To actually copy data on a partition, mount the partition by referencing the device node as you would with a regular disk:

mkdir -p /mnt/usb && mount /dev/mapper/loop0p1 /mnt/usb

You can now copy files to the image. When you're finished, unmount the partition again:

umount /dev/mapper/loop0p1

Once you're finished with the image entirely, release the mapped resources using kpartx. You need to do this if you want to manipulate (e.g. move or copy) the image file.

kpartx -d usb.img