Firewalls prevent attacks by examining network traffic and enforcing security policies. They can block unauthorized access attempts, filter out malicious content, and prevent certain network-based attacks.