Say you're getting consistent spam from IPs belonging to the same hosting provider

  1. Lookup the latest IP - https://asnlookup.com/ipv4/
  2. Copy all their IPv4 CIDRs into a text editor
  3. Perform a find/replace on those CIDRs to turn each one into the following command (you can leave the rule number the same for all of them, it just ensures the rules come first):
ufw insert 1 deny from to any

To see your rules:

ufw status numbered

To delete rule number 2:

ufw delete 2