最近做一個可執行shell調度的需求,要求用戶輸入shell,然后后台定時調度運行。實現大致為:保存用戶的輸入,設定時間,crontab定時執行用戶的輸入。但這里涉及到一個安全問題,如何確定用戶的輸入是安全的?
最初的想法是過濾危險命令,比如rm -rf /
之類的。后來,索性把用戶的命令丟到一個特殊文件內,以一個權限很小的用戶去執行用戶命令就好了。
於是寫好的腳本大致如下
sudo runuser -l 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
注釋掉這兩個就好了。