Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my sudo command in bash cannot 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 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?

like image 365
Judking Avatar asked Aug 11 '26 10:08

Judking


1 Answers

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).

like image 139
Basile Starynkevitch Avatar answered Aug 13 '26 03:08

Basile Starynkevitch