1

In /etc/cron.d/myjob, I create a cron task of running a bash script and redirect its stdout and stderr to a log file. The script contains a line of sudo running a command.

In the log file:

sudo: no tty present and no askpass program specified

Does that cause some problem that needs my attention?

I was wondering if cron tasks in /etc/cron.d/ files are supposed to not contain sudo?

Thanks.

Tim
  • 101,790
  • The script contains sudo. The script is supposed to run both with and without cron. I am not supposed to modify the script just for running it with cron and /etc/cron.d/myjob – Tim Oct 31 '18 at 00:32

1 Answers1

7

"Supposed" is a judgement call.

Commands called from /etc/cron.d/ are run as a specified user (either root or any other one; it's defined in the cron line). So, normally, there's no need for sudo.

However if you do have a script that calls sudo then you need to make sure the sudoers entry is correct. In particular:

  • Make sure the entry is assigned to the user running the script (this may be root)
  • Make sure the entry has the NOPASSWD attribute set so it can run without anyone needing to enter a password.

The error you're seeing is because the sudo command need a password, but there's no terminal to provide it.

A well written script would detect if it was running with the right permissions and not call sudo at all, but there's a lot of bad scripts :-)

  • Thanks. (1) I was wondering what "the sudoers entry" is? In /etc/sudoers, do you mean add an entry for the script? If the script can be run by any one (root or not), how can I specify that in the entry? (2) Does the sudo error means that sudo command failed? (3) In the cron job line in the crontab file, I specify a nonroot user in the user field, and a shell script which contains sudo for superuser privilleges. So what shall I do instead? – Tim Nov 01 '18 at 04:24
  • For (3), there is an example here https://unix.stackexchange.com/questions/478897/does-cron-modify-execution-environment-and-make-tor-servce-not-change-exit-node – Tim Nov 01 '18 at 04:42
  • (4) "A well written script would detect if it was running with the right permissions and not call sudo at all, but there's a lot of bad scripts" https://unix.stackexchange.com/questions/479055/shell-script-use-sudo-inside-it-vs-run-it-with-sudo#479055 – Tim Nov 01 '18 at 11:02