Skip to content

Instantly share code, notes, and snippets.

@CalebWhiting
Last active October 17, 2017 16:19
Show Gist options
  • Save CalebWhiting/9a3b7511169fa7bc3840d59d636c3cfc to your computer and use it in GitHub Desktop.
Save CalebWhiting/9a3b7511169fa7bc3840d59d636c3cfc to your computer and use it in GitHub Desktop.
ufw-replace
#!/bin/bash
# Syntax: 'ufw-replace <comment> <ufw parameter>...'
# Example: 'ufw-replace open-torrent-port allow 40340/tcp'
comment="$1"
if [ "$comment" = '' ]; then echo 'No comment provided!' && exit -1 ; fi
shift
args="$@"
if [ "$args" = '' ]; then echo 'Too few arguments' && exit -1 ; fi
#####################################################################
echo "Looking for rules with comment: '$comment'"
indices=""
while read -rd $'\n' line
do
if [[ "$line" != *#$' '$comment ]]; then continue; fi
index=${line#*\[}
index=${index%]*}
index=${index/' '/}
if [ "$indices" == '' ]; then indices="$index"; else indices="$indices $index"; fi
done < <(ufw status numbered)
#####################################################################
echo "Removing indices [ ${indices/ /, } ]"
# reverse indices so that the rules with a higher index are removed first
for index in $(echo $indices | awk '{ for (i=NF; i>1; i--) printf("%s ",$i); print $1; }')
do
echo $'\t'"Removing rule at index: $index"
echo -n $'\t'
ufw --force delete $index
done
#####################################################################
cmd="ufw $args comment $comment"
echo "Creating new rule ($cmd)"
$cmd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment