Why can't my sudo command in bash be executed via crontab?
Here's my simple runme.sh:
#!/bin/bash
/bin/echo 'CbEYKFKt' | /usr/bin/sudo -S /bin/su -c "whoami;/etc/init.d/iptables stop"
In which 'CbEYKFKt'
is the password for the current user: samX, which has the root privilege (added "samX ALL=(ALL:ALL) ALL"
in visudo
). I intend to stop iptables at a specific time in the crontab, but nothing happened to the iptables service when the time was right. However, if I execute bash runme.sh
, it works fine.
My crontab looks like this:
58 16 * * * /bin/bash /home/data/samX/runme.sh 2>&1 > /home/data/samX/log_cron
Nothing will be printed in the log_cron. Is there something wrong with my code? Thanks in advance.
PS The
error will be printed after I have moved 2>&1
to the end:
sudo: sorry, you must have a tty to run sudo
Does anyone know what this means?
source to share
Authentication utilities such as sudo
usually read the password from the controlling terminal (for example, through /dev/tty
, see tty (4) ) rather than from standard input. (But you can pass -S
in sudo
to ask it to read the password to stdin)
You can use expect (which can work with terminals), but you can simply configure your own /etc/sudoers
to disable password verification.
For example, you might have a string like
%sudo ALL=NOPASSWD: ALL
in your file /etc/sudoers
. This will allow any member of the group to sudo
use sudo
without entering a password.
This, of course, opens a hole in your computer. Do this at your own risk.
Finally, you can neatly wrap your script in a setuid executable (write such a program carefully in C, then the chmod u+s
executable).
source to share