-1

I need help with the following Bash v4.1.2 script.

#!/bin/bash

IP=$1
IPTABLES=/sbin/iptables
$IPTABLES -I INPUT -s $IP -j DROP
echo $IPTABLES -I INPUT -s $IP -j DROP |wall

The variables, IP and IPTABLES, get populated in the echo but the line above is not executed. The echo outputs...

/sbin/iptables -I INPUT -s 1.2.3.4 -j DROP

...which is syntactically correct and works if executed manually.

I don't know Bash so I'm struggling to debug this elementary script. I see some scenarios where commands are left bare as I have mine and some that are wrapped in $() (with and without quotes). I've also tried using backticks and quoting various parts of the command. The echo piped through wall only exists for debugging.

I found a basically identical post at Bash script commands not working in cron. My script is not running from cron though.

=== EDIT ===
Added for @Barmar

[root@server tmp]# bash -x /bin/netfilter-drop.sh 
+ IP=1.2.3.4
+ IPTABLES=/sbin/iptables
+ /sbin/iptables -I INPUT -s 1.2.3.4 -j DROP
+ wall
+ echo /sbin/iptables -I INPUT -s 1.2.3.4 -j DROP
[root@server tmp]# 
Broadcast message from root@server (Thu Dec 29 12:46:44 2016):

/sbin/iptables -I INPUT -s 1.2.3.4 -j DROP
^C
[root@server tmp]#
10
  • It should work fine. What makes you think it's not executed? Commented Dec 29, 2016 at 18:30
  • The rule is not added to netfilter. The rule is not displayed by iptables. Commented Dec 29, 2016 at 18:31
  • 2
    Are you running it as root? Commented Dec 29, 2016 at 18:35
  • 1
    The wall makes me think you're not running this from a terminal and therefore can't see all the helpful error messages that the script produces. Add exec &> /tmp/mylog to the start of the script, run it however you do it, then look at the file. If you're invoking it from as web server, @gniourf_gniourf guessed your problem Commented Dec 29, 2016 at 18:45
  • 1
    @thatotherguy and @gniourf_gniourf: Aye! iptables v1.4.7: can't initialize iptables table filter: Permission denied (you must be root) Perhaps iptables or your kernel needs to be upgraded.. So the problem is my sudo. That output was revealed by @thatotherguy's exec suggestion. Commented Dec 29, 2016 at 18:57

1 Answer 1

0

I had initially only given sudo access to run the posted Bash script. The problem was not the script, rather it was permissions. I needed to give additional sudo access to run iptables in my sudoers. Fixed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.