Cron – Troubleshooting Shell Scripts Not Working with Crontab

cron

I have a little VPS I run apache and a Minecraft server on. I don't ever turn it off, but should I restart it for some reason, IPTables blocks most of my ports, including port 80. I've tried so many different suggestions on fixing this, but with no luck. Also, since the provider is OVH, the support is… lacking.

So, I've created a workaround, which I'm happy with. I created a simple shell script file to open certain ports I need opened on restart (80 and 25565 for now). The important ones such as 21 and 22 are not affected on restart.

The script looks like this:

iptables -I INPUT -p tcp --dport 80 -j ACCEPT
iptables -I INPUT -p udp --dport 80 -j ACCEPT
iptables -I INPUT -p tcp --dport 25565 -j ACCEPT
iptables -I INPUT -p udp --dport 25565 -j ACCEPT
/sbin/service iptables save

When I manually run it by typing /iptdef.sh, it runs fine, the ports become open and it's all good.

Of course, it's not practical having to remember to run it every time I restart the server, so I added a crontab. The problem is, it doesn't work/run. This is my crontab file:

*/5 * * * * /backup2.sh
*/55 * * * * /backup3.sh
@reboot /iptdef.sh
* * * * *  /iptdef.sh

The first two lines work. They are just simple scripts that make a backup of a folder for me. The second two lines are what's not working.

Is there a chance that perhaps it's not possible to run iptables commands from a cron? It sounds silly, but I can't see any other reason for it not to work. The scripts have the correct permissions.

Best Answer

It's because cron forcibly sets PATH to /usr/bin:/bin. You need to invoke iptables as /sbin/iptables or add PATH=/usr/sbin:/sbin:/usr/bin:/bin in your script or crontab. See crontab(5) for details.

Related Question