Skip to content

Instantly share code, notes, and snippets.

@JeffCarpenter
Created September 6, 2023 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeffCarpenter/8ffd4482f19bc8f9594f059b4be222da to your computer and use it in GitHub Desktop.
Save JeffCarpenter/8ffd4482f19bc8f9594f059b4be222da to your computer and use it in GitHub Desktop.
Bash function to add or update a firewalld policy for accepting incoming traffic on a specified port.
#!/bin/bash
# Function to add or update firewalld policy
add_or_update_firewalld_policy() {
local protocol=$1
local port=$2
local zone=$3
# Check if the rule already exists
if firewall-cmd --zone=$zone --query-port=$port/$protocol; then
echo "Rule already exists for $port/$protocol in zone $zone."
return 0
fi
# Add the rule
if firewall-cmd --zone=$zone --add-port=$port/$protocol --permanent; then
echo "Successfully added $port/$protocol to zone $zone."
# Reload the firewall
firewall-cmd --reload
else
echo "Failed to add $port/$protocol to zone $zone."
exit 1
fi
}
# Test the function
for zone in home work internal public; do
add_or_update_firewalld_policy "udp" "60001" $zone
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment