Detecting USB Thumb Drive when Ready in Linux Shell Script - linux

I am a Windows admin and dev, I do not generally work with Linux so forgive me if this is in some way obvious.
I have a not so good Linux box, some older version of Open SUSE, and I have a script that unmounts the USB thumb drive, formats it, and then waits for the device to become ready again before it runs a script that does a copy/MD5 checksum verification on the source and destination file to ensure the copy was valid. The problem is that on one box the USB thumb drive does not become ready after the format in a consistent way. It takes anywhere from 1 to 2+ minutes before I can access the drive via /media/LABELNAME.
The direct path is /dev/sdb but, of course, I cannot access it directly via this path to copy the files. Here is my shell script as it stands:
#!/bin/bash
set -e
echo "Starting LABELNAME.\n\nUnmounting /dev/sdb/"
umount /dev/sdb
echo "Formatting /dev/sdb/"
mkfs.vfat -I -F32 -n "LABELNAME" /dev/sdb
echo "Waiting on remount..."
sleep 30
echo "Format complete. Running make master."
perl /home/labelname_master.20120830.pl
Any suggestions? How might I wait for the drive to become ready and detect it? I have seen Detecting and Writing to a USB Key / Thumb DriveAutomatically but quite frankly I don't even know what that answer means.

It seems that you have some automatic mounting service running which detects the flash disk and mounts the partition. However, you already know what the partition is, so I recommend that you simply mount the disk in your script, choosing a suitable mount point yourself.
mkfs.vfat -I -F32 -n "LABELNAME" /dev/sdb
echo "Format complete, remounting"
mount /dev/sdb $mountpoint #<-- you would choose $mountpoint
echo "Running make master."
perl /home/labelname_master.20120830.pl

Related

How to determine in bash if / mountpoint was mounted from other OS?

Im writing shell script to check if user may be doing some nasty things in Linux enviroment. One check i would like to do is determine if / filesyste was mounted using external OS (like using live SO) in previous mount.
First i think to exec script when boot to get the mount time in previous boot using journalctl and actual last mount using tune2fs, to compare it. But last mount using tune2fs gets current mount, not previous, because system is mounted when ckecks it.
Any idea to solve it?
Thanks!
dmesg's output shows about the mounting of / (and other infos as well). If your current OS's dmesg's output has that info, it was mounted by the current system.
You can use the output of dmesg in your script like :
#!/bin/bash
number=$(dmesg | grep -c "sdaN")
if [ $number == 0 ]; then
echo "It was not mounted by the current system"
else
echo "It was mounted by the current system"
fi

Shell Script Disk Image Analysis

I’m a beginner programmer and I'm try to learn how to successfully mount a disk image and analyse it but can't fine any guides online or any mention on web pages.
I’ve set myself the task as I’m thinking of joining a computer forensics course next year and believe these skills will give me a head start.
This is the code I've made so far but I've become stuck. I want the script to be able to extract command history data for all users, and also log successful and unsuccessful login attempts from log files such as /var/log/wtmp.
I’m not exactly looking for someone to complete the code (as that would be counterproductive) but to point me towards hints and tips, guides and tutorials to get over these early stage of programming.
#!/bin/bash
mount="/myfilesystem"
if grep -qs "$mount" /proc/mounts; then
echo "It's mounted."
else
echo "It's not mounted."
mount "$mount"
if [ $? -eq 0 ]; then
echo "Mount success!"
else
echo "Something went wrong with the mount..."
fi
fi
sudo fdisk -l | grep/bin /sbin
For mounting a filesystem, you need two arguments at least.
The image file or block device to be mounted and
The place where to mount it in your filesystem
So, if you want to mount some external USB drive, that e.g. shows as /dev/sda and has a single partition (sda1), you need to do the following:
Find or create a directory to mount your device (easiest as root), say you created a directory /root/mountpoint
Execute the mount command: mount /dev/sda1 /root/mountpoint
You then can step into the mounted filesystem cd /root/mountpoint and look around.
Just as a sidenote: For forensics, you should always draw an image from the device (e.g. dd if=/dev/sda1 of=/root/disk.img) to avoid destroying any evidence and then mount it through the loop driver (losetup /dev/loop1 /root/disk.img; mount /dev/loop1 /root/mountpoint).
Hope this gives you a hint to start over...

Change location of /etc/fstab

I have written a script which requires to read a few entries in /etc/fstab. I have tested the script by manually adding some entries in /etc/fstab and then restored the file to its original contents, also manually. Now I would like to automate those tests and run them as a seperate script. I do, however, not feel comfortable with the idea of changing /etc/fstab altered. I was thinking of making a backup copy of /etc/fstab, then altering it and finally restoring the original file after the tests are done. I would prefer it if I could temporarily alter the location of fstab.
Is there a way to alter the location of fstab to, say, /usr/local/etc/fstab so that when mount -a is run from within a script only the entries in /usr/local/etc/fstab are processed?
UPDATE:
I used bishop's solution by setting LIBMOUNT_FSTAB=/usr/local/etc/fstab. I have skimmed the man page of mount on several occasions in the past but I never noticed this variable. I am not sure if this variable has always been there and I simply overlooked it or if it had been added at some point. I am using mount from util-linux 2.27.1 and at least in this version LIBMOUNT_FSTAB is available and documented in the man-page. It is in the ENVIRONMENT section at the end. This will make my automated tests a lot safer in the future.
UPDATE2:
Since there has been some discussion whether this is an appropriate programming question or not, I have decided to write a small script which demonstrates the usage of LIBMOUNT_FSTAB.
#!/bin/bash
libmount=libmount_fstab
tmpdir="/tmp/test_${libmount}_folder" # temporary test folder
mntdir="$tmpdir/test_${libmount}_mountfolder" # mount folder for loop device
img="$tmpdir/loop.img" # dummy image for loop device
faketab="$tmpdir/alternate_fstab" # temporary, alternative fstab
# get first free loop device
loopdev=$(losetup -f)
# verify there is a free loop device
if [[ -z "$loopdev" ]];then
echo "Error: No free loop device" >&2
exit 1
fi
# check that loop device is not managed by default /etc/fstab
if grep "^$loopdev" /etc/fstab ;then
echo "Error: $loopdev already managed by /etc/fstab" >&2
exit 1
fi
# make temp folders
mkdir -p "$tmpdir"
mkdir -p "$mntdir"
# create temporary, alternative fstab
echo "$loopdev $mntdir ext2 errors=remount-ro 0 1" > "$faketab"
# create dummy image for loop device
dd if=/dev/zero of="$img" bs=1M count=5 &>/dev/null
# setup loop device with dummy image
losetup "$loopdev" "$img" &>/dev/null
# format loop device so it can be mounted
mke2fs "$loopdev" &>/dev/null
# alter location for fstab
export LIBMOUNT_FSTAB="$faketab"
# mount loop device by using alternative fstab
mount "$loopdev" &>/dev/null
# verify loop device was successfully mounted
if mount | grep "^$loopdev" &>/dev/null;then
echo "Successfully used alternative fstab: $faketab"
else
echo "Failed to use alternative fstab: $faketab"
fi
# clean up
umount "$loopdev" &>/dev/null
losetup -d "$loopdev"
rm -rf "$tmpdir"
exit 0
My script primarily manages external devices which are not attached most of the time. I use loop-devices to simulate external devices to test the functionality of my script. This saves a lot of time since I do not have to attach/reattach several physical devices. I think this proves that being able to use an alternative fstab is a very useful feature and allows for scripting safe test scenarios whenever parsing/altering of fstab is required. In fact, I have decided to partially rewrite my script so that it can also use an alternative fstab. Since most of the external devices are hardly ever attached to the system their corresponding entries are just cluttering up /etc/fstab.
Refactor your code that modifies fstab contents into a single function, then test that function correctly modifies the dummy fstab files you provide it. Then you can confidently use that function as part of your mount pipeline.
function change_fstab {
local fstab_path=${1:?Supply a path to the fstab file}
# ... etc
}
change_fstab /etc/fstab && mount ...
Alternatively, set LIBMOUNT_FSTAB per the libmount docs:
LIBMOUNT_FSTAB=/path/to/fake/fstab mount ...

bash command to force file closure on usb drive

I thought doing a sync in my bash script would force the file to be completely written out. When I looked at the thumb drive, it showed all the files I had copied, but after a power supply failure, the usb drive showed 0 files. Do I have to eject the drive manually or is there something I can do programmatically in my script?
If you want to eject the usb device from your bash script a simple umount on the device should do the trick. For example
mount /dev/usb /mnt/usb
# Your copy operations here... then on success:
umount /mnt/usb
you can also try to use the linux sync instruction that syncronize writing over disk if you're usb key is using a journalized file system

programmatically detect SD card write protect

Back in the good-old days of floppy, if you enable write protection of a floppy, DOS would kindly tell you that you cannot write to it. Now we have SD card that can hold the content of thousands of floppy and we still have the write protection - and it's handy sometime. But nobody is able to tell me I can't write to it, at least on Linux. I have a lovely script that partition and format a SD card in a way I like. It took me 1/2 hour of debugging just to find out that the SD card is write-protected.
So the question, is there a way that the software can detect such condition?
Thanks,
The driver knows when the card is write-protected, and it actually warns when you mount it via command line:
# mount /dev/sdc1 /media/flash
mount: block device /dev/sdc1 is write-protected, mounting read-only
In case you would like to check it yourself at device level, you can use the hdparm command to query read-only status of disk device, including SD card and USB flash drive in general. This program should be available in most GNU/Linux distributions, commonly in a package named "hdparm".
If you are not root, be sure to specify full path to the hdparm command; and this assumes you have read permission on your card of course.
For example: my SD card is inserted, detected as /dev/sdc, and write protection tab is at Unlock:
$ /sbin/hdparm -r /dev/sdc
/dev/sdc:
readonly = 0 (off)
When I slided the write protection tab to Lock, re-insert the card, and run the command again:
$ /sbin/hdparm -r /dev/sdc
/dev/sdc:
readonly = 1 (on)
If you would like to do it in shell script, you can try something like:
READONLY=`/sbin/hdparm -r /dev/sdc 2>&1 | sed -n 's/^.*= *\([01]\) .*$/\1/p'`
if [ "$READONLY" = "0" ]
then
echo Card is writable.
else
echo Card is not writable.
fi
Note: If you prefer to do it in C, you can try either:
Opening the device file in write mode and see if it fails with errno value EROFS (Read-only file system), or...
Opening the device file in read mode, then issue ioctl() named BLKROGET, and check if the result value is nonzero; this is the way hdparm work.

Resources