Using iptables without root privileges
Solution 1
Set the setuid bit on the script, so that it always runs as root.
chown root myscript
chmod u+s myscript
Solution 2
Based on another comment you made here the issue you're experiencing is bash cannot find the script you are trying to run.
When you are running a script or command that isn't in one of the paths defined in your $PATH
environment setting you need to provide the absolute or relative path for it. For example:
- If the script is in
/usr/local/bin
you need to run/usr/local/bin/scriptname.sh
. - If the script is in your home directory you need to run either
/home/username/scriptname.sh
or~/scriptname.sh
. - Alternatively you can change into that directory and call it with
./
like so:./scriptname.sh
Also you can update your $PATH
environment setting with the path to the script by modifying .bash_profile
, .bashrc
, or .profile
, depending on what env file you're using.
Related videos on Youtube
dev_sanketsr
Updated on September 18, 2022Comments
-
dev_sanketsr over 1 year
When running the following script as user
ec2-user
, I get the error messageiptables v1.4.18: can't initialize iptables table filter: Permission denied (you must be root)
Script:
#!/bin/sh # Offending IP as detected by mod_evasive # Add the following firewall rule (block IP) $IPTABLES -I INPUT -s $IP -j DROP
How can I run
iptables
as a non-root user to block a IP address?NB: This script is usually called by mod_evasive
-
Xavier Lucas over 9 yearsBe very careful with that, be sure that
$IPTABLES
var is the right absolute path to the binary. -
dev_sanketsr over 9 years@XavierLucas: The path is correct: "IPTABLES="/sbin/iptables"
-
-
dev_sanketsr over 9 yearsHi Michael, when trying to run the script, I do get the error message: command not found. What permissions would I need to change? Any idea?
-
Michael Hampton over 9 yearsWhat command is not found?
-
dev_sanketsr over 9 yearsThe script itself: When I enter the command in bash: "sudo ban_ip.sh 94.201.234.1xx", I do get: "sudo: ban_ip.sh: command not found". But the script file is there.
-
dev_sanketsr over 9 years@XavierLucas: With or without sudo: It does not work. I am in the same directory as the script when trying to execute it.
-
Xavier Lucas over 9 yearsYou are not using the absolute path. It doesn't matter in which directory you are.
-
Xavier Lucas over 9 yearsWhat's the point putting the script at the root of the filesystem ? Also, you should always use
visudo
wrapper instead of editing any sudoers file, that's why it's read-only by default. -
geocar over 9 yearsYou can put files wherever you want, but then you need to explain that all the other paths need to change.
-
Woodrow Douglass about 8 yearsusing sudo to gain root privileges is not the same as accomplishing the task without root privileges...