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 current user: samX, who has the root privilege (have appended "samX ALL=(ALL:ALL) ALL" in visudo). I intend to stop iptables at a specific time in crontab, but nothing happened to iptables service when the time is up. Nevertheless, if I execute bash runme.sh, it will works fine.
My crontab is as follows:
58 16 * * * /bin/bash /home/data/samX/runme.sh 2>&1 > /home/data/samX/log_cron
Nothing will be printed to log_cron file. Is there anything wrong with my code? Thanks in advance.
P.S.
A error is printed after I moved 2>&1 to the end:
sudo: sorry, you must have a tty to run sudo
Does anyone know what's that mean?
Authentification utilities like sudo are generally reading the password from the controlling terminal (e.g. thru /dev/tty, see tty(4)), not from standard input. (But you could pass -S to sudo to ask it to read password on stdin)
You could use expect (which is able to deal with terminals), but you could simply configure your /etc/sudoers to disable password checking.
For example, you could have a line like
%sudo ALL=NOPASSWD: ALL
in your /etc/sudoers file. It would allow any member of the sudo group to use sudo without typing any password.
This of course opens a security hole in your computer. Do that at your own risk.
At last, you could carefully wrap your script in a setuid executable (write carefully such a program in C, then chmod u+s the executable).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With