Deleting all UFW rules for a specific port number
if you want to delete rules based on a specific port number, use this (for example, port 3000 in this case) :
while true; do \
rule_number=$(\
ufw status numbered \
| awk '/(ALLOW|DENY) IN/ && $0 ~ /\<(3000)\>/{gsub(/[\[\]]/, "");\
print $1; \
exit}'\
); \
if [ -z "$rule_number" ]; then \
break; \
else \
sudo yes \
| ufw delete $rule_number --force; \
fi; \
done
This relists and retrieves the rule numbers each time again and again considering that the rule numbers will change.
Explaination
while true; do
initiates an infinite loop, as the condition
"true
" is always met.
rule_number=$(ufw status numbered | awk '/(ALLOW|DENY) IN/ && $0 ~ /\<(3000)\>/{gsub(/[\[\]]/, ""); print $1; exit}')
: This command starts a sub-shell to retrieve the first rule number from the ufw (Uncomplicated Firewall) status output that matches certain criteria.
(ALLOW|DENY) IN
: Matches lines containing "ALLOW IN" or "DENY IN". $0 ~ /\<(3000)\>/
: Matches lines where the number "3000" appears as a separate word.
{gsub(/[\[\]]/, ""); print $1; exit}
:
Performs string manipulation to remove square brackets from the line (if present), and prints the first field (the rule number). The exit
statement ensures that only the first match is captured. The retrieved rule number is stored in the variable rule_number
.
if [ -z "$rule_number" ]; then break;
: This conditional statement
checks if the rule_number
variable is empty. If it is empty (i.e., no
rule number is found), the script breaks the loop and ends. If the
variable is not empty, the script continues to the next step.
else sudo yes | ufw delete $rule_number --force; fi;
: This command
uses ufw to delete the rule specified by the captured rule_number. The --force
flag is used to avoid interactive confirmation prompts. The sudo yes command is used to automatically answer "yes" to any prompts that may appear.
The loop continues from the beginning, repeating the process to find
the next matching rule number and delete it. This continues until
there are no more matching rules, at which point the loop breaks and
the script ends.
Hope that helps!