crontab不能执行sudo:抱歉,您必须拥有一个终端来执行 sudo

最近做一个可行shell调度的需求,要求用户输入shell,然后后台定时调度运行。实现大致为:保存用户的输入,设定时间,crontab定时执行用户的输入。但这里涉及到一个安全问题,如何确定用户的输入是安全的?

最初的想法是过滤危险命令,比如rm -rf /之类的。后来,索性把用户的命令丢到一个特殊文件内,以一个权限很小的用户去执行用户命令就好了。

于是写好的脚本大致如下

sudo runuser -l -u etl_shell -m -c " function make_dir(){ local dir_name=\$1 if [ ! -d \$dir_name ];then mkdir -p \$dir_name else echo dir \${dir_name} exist fi } function touch_file(){ local file_name=\$1 if [ ! -f \$file_name ];then touch \$file_name else echo file \${file_name} exist fi } make_dir $script_temp; touch_file ${script_file} echo \"$tar_command\" > ${script_file}; chmod 700 ${script_file}; sh ${script_file}; "

手动执行没有问题,命令确实以另一个用户执行了。添加到定时任务crontab。结果发现运行失败,错误是:

udo:抱歉,您必须拥有一个终来执行 sudo

不允许非终执行sudo,那只能以root用户来做这件事。而我又没有root用户,只好修改这个规则,允许crontab 执行sudo

找到/etc/sudoers

# # Disable "ssh hostname sudo <cmd>", because it will show the password in clear. # You have to run "ssh -t hostname sudo <cmd>". # #Defaults requiretty # # Refuse to run if unable to disable echo on the tty. This setting should also be # changed in order to be able to use sudo without a tty. See requiretty above. # #Defaults !visiblepw

注释掉这两个就好了。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyzywg.html