Expect script does not work under crontab

a 夏天 提交于 2019-11-30 08:42:35

I had the same issue, except that my script was ending with

interact

Finally I got it working by replacing it with these two lines:

expect eof
exit
sof

Changing interact to expect eof worked for me!

Needed to remove the exit part, because I had more statements in the bash script after the expect line (calling expect inside a bash script).

There are two key differences between a program that is run normally from a shell and a program that is run from cron:

  1. Cron does not populate (many) environment variables. Notably absent are TERM, SHELL and HOME, but that's just a small proportion of the long list that will be not defined.
  2. Cron does not set up a current terminal, so /dev/tty doesn't resolve to anything. (Note, programs spawned by Expect will have a current terminal.)

With high probability, any difficulties will come from these, especially the first. To fix, you need to save all your environment variables in an interactive session and use these in your expect script to repopulate the environment. The easiest way is to use this little expect script:

unset -nocomplain ::env(SSH_AUTH_SOCK)   ;# This one is session-bound anyway
puts [list array set ::env [array get ::env]]

That will write out a single very long line which you want to put near the top of your script (or at least before the first spawn). Then see if that works.

Jobs run by cron are not considered login shells, and thus don't source your .bashrc, .bash_profile, etc.

If you want that behavior, you need to add it explicitly to the crontab entry like so:

$ crontab -l
0 13 * * * bash -c '. .bash_profile; etc ...'
$
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!