Skip to content

Instantly share code, notes, and snippets.

@gene1wood
Last active January 13, 2024 19:06
Show Gist options
  • Save gene1wood/fc4eff88aba7a90a2b614ad6932f3b09 to your computer and use it in GitHub Desktop.
Save gene1wood/fc4eff88aba7a90a2b614ad6932f3b09 to your computer and use it in GitHub Desktop.
Script to mount and unmount all /etc/fstab mount points that use NFS over Netbird
#!/bin/bash
if [ -z "$1" -o "$1" = "mount" ]; then
action=mount
elif [ "$1" = "umount" ]; then
action=umount
elif [ "$1" = "wait" ]; then
action=wait
else
echo "missing action"
exit 1
fi
if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit 1
fi
function in_subnet {
# Determine whether IP address is in the specified subnet.
#
# Args:
# sub: Subnet, in CIDR notation.
# ip: IP address to check.
#
# Returns:
# 1|0
#
# https://unix.stackexchange.com/a/465372/22701
local ip ip_a mask netmask sub sub_ip rval start end
# Define bitmask.
local readonly BITMASK=0xFFFFFFFF
# Read arguments.
IFS=/ read sub mask <<< "${1}"
IFS=. read -a sub_ip <<< "${sub}"
IFS=. read -a ip_a <<< "${2}"
# Calculate netmask.
netmask=$(($BITMASK<<$((32-$mask)) & $BITMASK))
# Determine address range.
start=0
for o in "${sub_ip[@]}"
do
start=$(($start<<8 | $o))
done
start=$(($start & $netmask))
end=$(($start | ~$netmask & $BITMASK))
# Convert IP address to 32-bit number.
ip=0
for o in "${ip_a[@]}"
do
ip=$(($ip<<8 | $o))
done
# Determine if IP in range.
(( $ip >= $start )) && (( $ip <= $end )) && rval=1 || rval=0
echo "${rval}"
}
# Carrier Grade NAT IP Range : 100.64.0.0/10
# Example /etc/fstab line
# 100.64.1.2:/export/example /data/example nfs noauto,nofail,noatime,nolock,intr,tcp,actimeo=1800 0 0
if [ "$action" = "wait" ]; then
while awk '$3 == "nfs4" {print $0}' /proc/mounts | grep --quiet .; do
sleep 1
done
else
grep -Ev "^\s*#|^\s*$" /etc/fstab | grep -E '^[0-9.]+:' | while read -r line; do
if [ $(in_subnet 100.64.0.0/10 ${line%%:*}) = 1 ]; then
dir=$(awk -F' ' '{print $2}' <<< "$line")
if [ "$action" = "umount" ]; then
if mountpoint --quiet "$dir"; then
echo "$action $dir"
$action "$dir"
fi
else
echo "$action $dir"
$action "$dir"
fi
fi
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment