我编写了一个脚本,该脚本接受用户的命令并运行大量服务器列表并写入单个文件。写入完成后,它会触发一封电子邮件。我的要求是:脚本应该在后台运行,完成后发送电子邮件。
我已经尝试过wait $PROC_ID &
- 但写入是在后台进行的,并且电子邮件会立即发送,其中包含空白数据。一旦数据写入文件完成,是否有可能在后台等待并触发邮件?
代码输出:
The output can be monitored in /tmp/Servers_Output_list.csv .....................Please Be Patient
Mail will get triggered once completed
代码如下,我提到了我的脚本的一个功能
for i in `cat $file_name`
do
ssh -q -o "StrictHostKeyChecking no" -o "NumberOfPasswordPrompts 0" -o ConnectTimeout=2 $i "echo -n $i;echo -n ",";$command3" 2>>/dev/null &
done >> $file_save &
PROC_ID=$!
echo " "
echo " The output can be monitored in $file_save....................Please Be Patient"
echo "Mail will get triggered once completed"
echo " "
wait $PROC_ID
while true; do
if [ -s $PROC_ID ];then
echo "$PROC_ID process running Please check"
else
mailx -s "Servers Command Output" -a $file_save <my [email protected]>
break;
fi
done &
exit 0;
fi
答案1
如果我理解正确的话,您想要运行 ssh 命令,等待完成并在后台发送邮件。这意味着该脚本可能会在 ssh 和邮件完成之前完成。
所以我提出以下解决方案:
#!/bin/bash
# Set to real file if you want "log output"
log_file=/dev/null
file_save=/whatever
command3=<some command here>
function exec_ssh
{
for i in $(cat $file_name); do
ssh -q -o "StrictHostKeyChecking no" -o "NumberOfPasswordPrompts 0" -o ConnectTimeout=2 $i "echo -n $i;echo -n ',';$1" 2>/dev/null &
done >> $file_save
wait
mailx -s "Servers Command Output" -a $file_save <my [email protected]>
}
# export function, so it is callable via nohup
export -f exec_ssh $command3
# clear file_save
>$file_save
# run exec_ssh in the background.
# nohup keeps it running, even when this script terminates.
nohup exec_ssh &>$logfile &
# Inform user
echo " The output can be monitored in $file_save....................Please Be Patient"
echo "Mail will get triggered once completed"
exit 0
函数 exec_ssh 完成所有工作并在后台运行nohup
。这样,当脚本完成时,甚至当终端关闭时,后台作业会继续运行。
我不确定当用户从系统注销时会发生什么。
答案2
或者
function doit () {
ssh -q -o "StrictHostKeyChecking no" -o "NumberOfPasswordPrompts 0" -o ConnectTimeout=2 $1 "echo -n $1;echo -n ",";$command3" 2>>/dev/null &
}
export -f doit
C=$(cat $file_name | wc -l)
cat $file_name | xargs -I {} -P $C bash -c "doit \"{}\"" >> $file_save
mailx -s "Servers Command Output" -a $file_save <my [email protected]>