Bash 脚本命令在 cron 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22984318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:10:00  来源:igfitidea点击:

Bash script commands not working in cron

linuxbashcron

提问by Tarek Sawah

I have the following bash script to read logs and check for brute force then block violating IP using iptables.

我有以下 bash 脚本来读取日志并检查蛮力,然后使用 iptables 阻止违反 IP。

#!/bin/bash
#blah blah run some commands to get the IP
iptables -A INPUT -s $p -j REJECT --reject-with icmp-host-prohibited
echo "BANNED $p FOR $COUNT ATTEMPTS" |wall

I did chmod 755. When I run the command from terminal it works fine. But when I setup a cronjob using crontab -eas root, it gets the IP and echos the "BANNED ..." message to the wall but nothing is added to the iptables list.

我做了 chmod 755。当我从终端运行命令时,它工作正常。但是,当我crontab -e以 root 身份设置 cronjob 时,它会获取 IP 并将“BANNED ...”消息回显到墙上,但没有向 iptables 列表添加任何内容。

PS. I tried both #!/bin/bashand #!/bin/shbut no luck.

附注。我都试过#!/bin/bash#!/bin/sh但没有运气。

回答by kpopovbg

Try to provide full path to iptables e.g.

尝试提供 iptables 的完整路径,例如

$ which iptables
/sbin/iptables

and than modify your script like that:\

而不是像这样修改你的脚本:\

#!/bin/bash
#blah blah run some commands to get the IP
/sbin/iptables -A INPUT -s $p -j REJECT --reject-with icmp-host-prohibited
echo "BANNED $p FOR $COUNT ATTEMPTS" |wall

回答by MLSC

Try the following solution should work for you:

尝试以下解决方案应该适合您:

cat cronjob
* * * * * /path/to/script.sh

Then:

然后:

chmod +x cronjob
chmod +x script.sh

/etc/init.d/crond start  #redhat based servers like centos
/etc/init.d/cron  start  #debian based servers like ubuntu

crontab cronjob

NOTE: Sometimes you need to enter full path of IPTABLES command if your rules aren't added to /etc/sysconfig/iptables.

注意:如果您的规则没有添加到/etc/sysconfig/iptables.