Is there a program on Debian to block an IP address temporarily just by launching a command (specifying the IP and the duration)?

With iptables/ip6tables alone I can create a rule, but I would then have to delete manually. I also use fail2ban, but I don't think I can block an arbitrary IP address that did not satisfy any of the fail2ban rules.

  • 1
    For example create the rule and schedule with at the rule deletion command, something like echo "iptables -d rest_of_rule" | at now+30m – Dan Jun 26 '15 at 17:23
  • @Dan This sound like a good solution. Actually, if you write an answer in the form of a little bash script that can take the IP and the duration as input parameters, I would accept it! – JoeWhite Jun 27 '15 at 7:35

You need to create an ipset so iptables can match against it. Note timeout 0 means the default is never expire.

ipset create temp_hosts hash:ip timeout 0
iptables -I INPUT 1 -m set -j DROP  --match-set temp_hosts src
iptables -I FORWARD 1 -m set -j DROP  --match-set temp_hosts src

Now that our set is created we can start adding ip addresses (timeout unit: seconds).

ipset add temp_hosts timeout 400

Note should you need these to survive a reboot you need to save and load the rules.

ipset save -f /path/ipset.save
ipset restore -f /path/ipset.save

These can be automated with cron or systemd.


Try this script, inspired by Dan's comment:

iptables -I INPUT -s $1 -j DROP
at ${2:-now+1hour} <<<"iptables -D INPUT -s $1 -j DROP"

Save it as /usr/local/sbin/blockip and run blockip or blockip now+2hours. By default the IP is blocked for 1 hour.

You can replace DROP with REJECT if you prefer REJECT semantics.

  • If you intend on a long lists of rejects, having a lot of rules will slow iptables down a lot. ipset has you covered all options together. You could end up with hundreds of cron jobs which is also less than ideal. – cybernard Dec 31 '16 at 5:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.